AJAX值发送错误 [英] AJAX value sending error
问题描述
您好我有问题,下面的脚本。这个问题我觉得对数据的谎言需要发送通过AJAX到PHP。
Hi I have problems with the script below. The problem I think lies on data that need to be sent to php via AJAX.
jQuery的
$('.send').live("click", function(){
$.ajax({
url:'foobar.php',
type:'post',
data: 'id=' + $(this).attr('id'),
dataType:'json',
contentType: 'application/json; charset=utf-8',
success: function(data) {
switch (data.status)
{
case "a":
alert(data.text);
break;
case "b":
alert(data.text);
break;
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert ("error: "+textStatus);
}
})
}
和,PHP
$id = $_REQUEST['id'];
switch ($id) {
case "foo":
$data["status"] = "a";
$data["text"] = "foo-foo";
echo json_encode($data);
break;
case "bar":
$data["status"] = "b";
$data["text"] = "bar-bar";
echo json_encode($data);
break;
}
但是,如果我这样做
but, if I do this
//data: 'id=' + $(this).attr('id'),
和改变这种
$id = 'foo';
剧本的工作就好了。我需要做的,使上述两个脚本可以工作吗?先谢谢了。
the script work just fine. What I need to do to make both script above can work? Thanks in advance.
推荐答案
我会把我的评论作为一个答案。
I will put my comment as an answer.
除了使用去precated jQuery的API,别人没有指出的是以下内容:
Apart from using a deprecated jQuery API, what others didn't point out is the following:
你是做在下面的线是什么:
What you are doing in the below line:
contentType: 'application/json; charset=utf-8',
是,你是有希望的服务器的HTTP实体将是一个JSON串,它不是这种情况。它实际上是通常的百分恩codeD字符串。 ( A = B和C = D急症= F
)。
如果你删除这一行,浏览器发送一个默认值的Content-Type为应用程序/ x-WWW-URL形式-CN codeD
。这将引发PHP解析HTTP实体等,给你的 $ _ REQUEST
阵列正确填充。
If you remove that line, the browser sends a default value Content-Type as application/x-www-url-form-encoded
. That would trigger PHP to parse the HTTP entity as such and give you as the $_REQUEST
array properly populated.
这篇关于AJAX值发送错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!