2011-09-23 87 views
0

如果我在下面的代码中将类型设置为'GET',它可以工作,但是我不能让它与'POST'一起工作。不能让jQuery ajax POST开始工作

ajaxPostTest.html ...

<html> 
<head> 
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.js"></script> 
<script type="text/javascript"> 

$(document).ready(function(){ 

    $.ajax({ 
     url: "ajaxPostTest_server.php", 
     data: {"fruit1": "rasp", "fruit2": "bramble"}, 
     type: 'POST', 
     dataType: 'json', 
     contentType: "application/json; charset=utf-8", 
     success: function(data){ 
      $("#returned").append(data.fruit1); 
      }, 
     error: function(jqXHR, textStatus, errorThrown){ 
      alert("error") ; 
      } 
     }); 
}); 

</script> 
</head> 
<body> 
<div id="returned">returned: </div> 
</body> 
</html> 

ajaxPostTest_server.php ...

<?php 
    echo json_encode($_REQUEST); 
?> 

浏览器的预期输出是...

returned: rasp 

我实际上试图与ASP.NET Web服务器交互,我想确认我的ajax正在工作(并且我正确理解ajax) - 首先 - 因此这个简化的代码。

Firebug的调试......

Response Headersview source 
Date Fri, 23 Sep 2011 14:57:37 GMT 
Server Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1 
X-Powered-By PHP/5.3.1 
Keep-Alive timeout=5, max=99 
Connection Keep-Alive 
Transfer-Encoding chunked 
Content-Type text/html 
Request Headersview source 
Host localhost 
User-Agent Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.18) Gecko/20110614 Firefox/3.6.18 
Accept application/json, text/javascript, */*; q=0.01 
Accept-Language en-gb,en;q=0.5 
Accept-Encoding gzip,deflate 
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 
Keep-Alive 115 
Connection keep-alive 
Content-Type application/json; charset=utf-8 
X-Requested-With XMLHttpRequest 
Referer http://localhost/My_Webs/temp/ajaxPostText1.html 
Content-Length 26 
Cookie PHPSESSID=mgvoacnluh3kad5pakafrd5kd1 

所有我在 '响应' 选项卡得到的是...

{"PHPSESSID":"mgvoacnluh3kad5pakafrd5kd1"} 

即我找不到我发送到服务器的数据在哪里。

+0

你可以使用萤火虫,并发布错误,或从控制台响应? – AJC

+0

为什么你将请求的内容类型设置为“application/json”?将其设置为“application/x-www-form-urlencoded”(默认值),然后重试。 – Niko

+0

@AJC。添加了对我的问题的回复。 – spiderplant0

回答

1

由于您的发送数据为 “应用/ JSON”,PHP不填充$ _ POST/$ _REQUEST。您需要以“application/x-www-form-urlencoded”的形式发送请求(您可以省略“Content-Type”参数,因为这是默认类型)。

+0

工作。我添加了与ASP.NET而不是PHP通信时似乎使用的Content-Type cos。另外GET似乎并不介意添加json内容类型。无论如何,现在我知道规则是什么,我可以得到它的工作。感谢您的解决方案和时间。 – spiderplant0

0

使用$ _POST而不是$ _REQUEST

+0

谢谢。试过 - 没有效果。 – spiderplant0