发送数据到一个网站获得一个JSON与PHP
问题描述:
我有一个问题,事情是,我正在阅读与jQuery的JSON文件,它运行良好,但现在我必须让它读取它PHP的,但事情是,我用一些数据来获得JSON与部分:发送数据到一个网站获得一个JSON与PHP
dataString = "id=" + id + "&todos=" + false;
$.ajax({
type: "POST",
url: "http://www.url.com/example",
data: dataString,
dataType: "json",
success: function(data, textStatus, jqXHR) {
而与此我没有问题,因为我是将数据发送到该网站,因此它可以给我的信息,我想,但我不知道该怎样做,在PHP的线索,我与
$str = file_get_contents('http://www.url.com/example.json');
$json = json_decode($str, true);
var_dump($str);
试图但是,当然,该网站及其回我nothi因为我没有发送数据
我希望有一种方法。谢谢!
答
如果第一个不存在且无法启用(非常罕见),则应使用curl
或fsockopen
。
你怎么在这里与curl
<?php
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'id' => $id,
'todos' => false
));
$json = json_decode(curl_exec($ch));
答
乔纳森·库恩是正确的。
下面是与stream_context_create一个例子:
<?php
$str = file_get_contents('http://www.url.com/example', false, stream_context_create(
array('http' =>
array('method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => 'id=idVal&todos=false'))));
?>
+0
我不鼓励这种方法,因为在服务器上禁用'allow_url_fopen'是一种很好的安全措施。但是,这教会了我'stream_context_create'的存在,因此谢谢你:P – Iazel 2014-10-17 19:02:52
因为你张贴与AJAX请求一起的数据,你需要使用[stream_context_create](http://php.net/manual/en/function .stream-context-create.php)构建一个上下文,用于更改发布和发送数据的方法。那就是如果你想使用file_get_contents。或者你可以使用卷曲,但你会以相同的结果结束。 – 2014-10-17 18:10:59