php - jQuery $.ajax() 到 PHP CURL

标签 php jquery ajax curl

我希望将以下内容翻译成 PHP CURL。

$.ajax({
  url:"MY_URL",
  cache: false,
  type: "POST",
  data: "",
  dataType: "xml",
  success: function(data) { 
    alert('Eureka!')
    }
});

我特别感兴趣的是弄清楚我必须如何更改以下内容才能将数据类型设置为 xml。以下代码无效:

$ch = curl_init('MY_URL');
curl_setopt($ch, CURLOPT_HEADER, 0); // get the header 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($ch,CURLOPT_HTTPHEADER,array (
      "Content-Type: xml; charset=utf-8",
      "Expect: 100-continue",
      "Accept: xml"
     ));

谢谢!

最佳答案

使用 phery,您可以以非常简单的方式完成(在 http://phery-php-ajax.net/ 中),过去 2 年我一直在改进和使用我的库:

// file would be curl.php
Phery::instance()->set(array(
  'curl' => function($data){
    $ch = curl_init($data['url']);
    curl_setopt($ch, CURLOPT_HEADER, 0); // get the header 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
    curl_setopt($ch,CURLOPT_HTTPHEADER,array (
      "Content-Type: xml; charset=utf-8",
      "Expect: 100-continue",
      "Accept: xml"
    ));
    $data = curl_exec($ch);
    curl_close($ch);
    return PheryResponse::factory()->json(array('xml' => $data)); 
  }
))->process();

然后使用 ajax 调用创建一个函数以使其可重用:

/* config would be {'url':'http://'} */
function curl(url){
  return phery.remote('curl', {'url': url}, {'target': 'curl.php'}, false);
}

curl('http://somesite/data.xml').bind('phery:json', function(event, data){
  // data.xml now contains the XML data you need
}).phery('remote'); // call the remote curl function 

关于php - jQuery $.ajax() 到 PHP CURL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13252394/

相关文章:

PHP DOMDocument实例化语法错误

php - 从其他行创建一行

javascript - 粘滞不工作

javascript - 创建给定数组中唯一的随机整数

javascript - 迭代数组

javascript - 将 $.ajax() 与不同的目录一起使用?

javascript - P2P Ajax图像传输

javascript - 将数据从 javascript 变量传递到 PHP 变量

php - 无法使用简单的 HTML 表单更改 MySQL 变量

javascript - .hasClass on.click 直到第二次 .click..ajax 异步才注册函数调用?