PHP服务器的JSON数据响应为空

时间:2010-02-25 17:17:23

标签: php jquery ajax json

我很难搞清楚这一个。似乎无论我尝试什么,PHP总是最终返回一个空数组。这是我的主文件的代码(index.php):

<script language="javascript" type="text/javascript">

$(document).ready(function(){

  $(".ajaxlink").click(function() {
    callServer();
    return false; //Stop link from redirecting
  });

});

var test = { "testName": "testValue" }
var testJSON = JSON.stringify(test);

function updatePage(data) {
  document.getElementById("testDiv").innerHTML = data;
}

function callServer() {
 $.ajax({
   type: "POST",
   url: "ajax/server.php",
   data: testJSON,
   success: function(data) {
     updatePage(data);
   },
   //Upon error, output message containing a little info on what went wrong
   error: function (XMLHttpRequest, textStatus, errorThrown) {
     alert('An Ajax error occured\ntextStatus = ' + textStatus + '\nerrorThrown = ' + errorThrown + '\nstatus = ' + XMLHttpRequest.status);
   }
 });
}

</script>

<div id="testDiv">Something here</div>

<a href="test1.htm" class="ajaxlink">Link!</a> <br>

当您单击“链接!”时,这基本上会运行callServer()函数。然后它将测试json数据,即{“testName”:“testValue”}发送到server.php。 Firebug报告说json数据确实发送到了server.php。

我的server.php看起来像这样:

<?php

print_r($_POST);

?>

这将在testDiv中返回以下内容:

Array
(
)

.ajax函数中的数据类型未定义,因此无论server.php文件吐出的输出是什么,它都应该是可读的。所有必要的库(json,jquery)也包含在我的文档中。我在Apache 2.2和PHP 5.3.1上运行它,但它在我的网络服务器(它是数千个网站的主机)上显示相同的内容。请求标头中使用的内容类型是'application / x-www-form-urlencoded; charset = UTF-8'因此应该正常工作。

感谢您的时间。 最好的祝福 索伦

3 个答案:

答案 0 :(得分:4)

我认为你以错误的方式发送数据。要么发送类似testName=testValue的字符串,要么将test中的值直接分配给data的{​​{1}}参数,并且不要使用.ajax()方法。

因为,如果您使用stringify,实际发送的数据将是(我假设,我不确定):

stringify

但这不是有效的参数字符串。

它应该是

形式

'{ "testName": "testValue" }'

因此直接使用'testName=testValue'.ajax()会将对象转换为合适的字符串:

test

答案 1 :(得分:0)

使用firefox和Live Http Headers扩展名。
通过这个,您将能够确切地看到问题所在,
Php或Js代码。

live http headers

答案 2 :(得分:0)

我不确定您的PHP脚本的输出是否为JSON格式。

如果您使用的是较新版本的PHP(您可以使用),则可以访问json_encode和json_decode函数。而不是做:

print_r($_POST);

尝试:

print json_encode($_POST);

如果您的PHP版本没有这些函数,您可以使用Zend Framework中的Zend_Json类等库,以便在输出之前将PHP变量编码为JSON。

当它返回时,它将是一个JSON格式的字符串。在jQuery.ajax调用中设置dataType应该将其计算为JS对象。如果不是,您要么必须在其上调用Javascript eval函数,要么(最好)使用JSON.parse(数据)。