簡體   English   中英

如何將POST請求從PHP發送到通常使用AJAX調用訪問的服務?

[英]How to send POST request from PHP to a service that is normally accessed using AJAX calls?

通過異步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”標頭設置為“ XMLHttpRequest”。

否則,請按照此答案中的步驟進行操作,除了您將使用POST注釋字段。

該答案建議了如何調試和逆向工程現有的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中的AJAX,但是如果您正在談論對外部站點進行GET和POST,則需要libcurl

http://php.net/manual/zh/book.curl.php

有很多例子;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM