【发布时间】:2012-11-07 01:16:54
【问题描述】:
我从 JQuery $.getJSON 函数调用 web 服务,它工作正常。
var p = {
'field1': 'value1',
'field2': 'value2',
'field3': 'value3'
};
$.getJSON('https://service:xxx@xxx.xxx.yyyyy.com.xx/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:xxx@xxx.xxx.yyyyy.com.xx/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:xxx@xxx.xxx.yyyyy.com.xx/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?两种情况下返回的格式不同
-
.getJSON 是一个获取请求。在 PHP 中,您使用的是发布请求。同样在 POSTFIELDS 中采用关联数组,但在您的第二次尝试中,您只给了它一个字符串。
标签: php json web-services curl callback