我從JQuery $ .getJSON函數調用webservice,它工作正常。如何使用參數和回調從PHP調用JSON Web服務?
var p = {
'field1': 'value1',
'field2': 'value2',
'field3': 'value3'
};
$.getJSON('https://service:[email protected]/service/search?callback=?', p, function(data) {
if (data[0]) {
// print results
} else {
// no results found
}
});
我想從PHP和CURL連接,但它不工作,它總是返回false。
//首先嚐試
$params = array( 'field1' => 'value1', 'field2' => 'value2', 'field3'=> 'value3');
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, 'https://service:[email protected]/service/search?callback=?');
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$result = curl_exec($ch); // return false instead of my JSON
//第二次嘗試
$data_string = json_encode($params);
$ch = curl_init('https://https://service:[email protected]/service/search?callback=?');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result2 = curl_exec($ch); //return false instead of my JSON
我做錯了嗎?
非常感謝,
是請求jsonp或json?返回的格式在兩種情況下都不相同 – Landon
.getJSON是一個獲取請求。在PHP中,您正在使用一個post請求。在POSTFIELDS中也需要一個關聯數組,但在第二次嘗試中,只給它一個字符串。 – Codeguy007