通过异步 HTTP 请求,我可以使用现有服务从数据库加载某些信息或将某些信息保存到数据库中。但至少据我所知,这些请求(AJAX)只能从客户端(例如 JavaScript 脚本)完成。
例如使用 jQuery ajax 方法:
$.ajax({
type: "POST",
url: someurl,
dataType: 'xml',
data: xmlString,
success: function(data) {
// some code here
}
});
如何从 PHP 脚本使用相同的服务?也就是说,我如何使用 POST 或 GET 方法“从 PHP 进行 AJAX 调用”?
最佳答案
您可以使用 cURL 库来访问相同的 URL。
您可能需要将“X-Requested-With” header 设置为“XMLHttpRequest”,以防接收服务检查。
否则,请按照 this answer 中的方式继续操作只不过您将使用 POST 注释字段。
This answer建议如何调试和逆向工程现有的 AJAX 服务。然后,您将能够使用例如SimpleXML 来解码答案,根据您发布的 jQuery 代码,该答案将以 XML 格式显示。
测试。
$url = 'http://your-url';
$fields = array(
'key' => 'value',
// other fields
);
$headers = array(
'X-Requested-With: XMLHttpRequest',
);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Note that you might have to set CURLOPT_POSTFIELDS to a urlification of
// $fields instead of an array, in case the service distinguishes form-data
// from url encoding.
curl_setopt($ch, CURLOPT_POST, True);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields);
// IMPORTANT: some AJAX services will expect inbound data to be coming JSON encoded, so if that is the case, you shall have to write instead
// curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$xml = curl_exec($ch);
curl_close($ch);
$xml = simplexml_load_string($xml);
print_r($xml);
关于php - 如何从 PHP 向通常使用 AJAX 调用访问的服务发送 POST 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12848089/