我正在尝试使用
XMLHttpRequest对象从表单发送
JSON数据.我可以使用以下函数发送数据. FireBug中没有显示错误,请求中的JSON数据显示为FireBug.
但是,我将数据发送到echo.PHP,简单地返回内容:
<?PHP print_r($_POST); print_r($_GET); foreach (getallheaders() as $name => $value) { echo "$name: $value\n"; } echo file_get_contents('PHP://input'); ?>
POST数组始终为空,但我可以看到file_get_contents返回的JSON字符串.这是怎么发生的?我究竟做错了什么?
echo.PHP的输出
Array ( ) Array ( ) Host: localhost User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0.2) Gecko/20100101 Firefox/10.0.2 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: eo,de-de;q=0.8,de;q=0.6,en-us;q=0.4,en;q=0.2 Accept-Encoding: gzip,deflate Connection: keep-alive Content-Type: application/json; charset=utf-8 Referer: http://localhost/form.html Content-Length: 88 Cookie: {{..to much data..}} Pragma: no-cache Cache-Control: no-cache {"type":"my_type","comment":"commented"}
发送功能:
function submit(){ var data={}; data.type=document.form.type.value; data.comment=document.form.comment.value; //get right XMLHttpRequest object for current browsrer var x=ajaxFunction(); var string = JSON.stringify(data); x.open('POST','echo.PHP',true); x.setRequestHeader('Content-type','application/json; charset=utf-8'); x.setRequestHeader("Content-length",string.length); x.setRequestHeader("Connection","close"); x.onreadystatechange = function(){ if (x.readyState != 4) return; if (x.status != 200 && x.status != 304) { alert('HTTP error ' + req.status); return; } data.resp = JSON.parse(x.responseText); if(data.resp.status=='success'){ alert('That worked!'); }else{ alert('That didn\'t work!'); } } x.send(string); return false; //prevent native form submit }
解决方法
您忘了在send函数中命名变量.
使用它的好方法是
使用它的好方法是
x.send('name1='+string+'&name2=value2');
鉴于此,我认为你将不得不改变内容长度标题.我不认为发送它是有用的.
您可以做的另一件事是尝试使用GET方法.
您还可以尝试通过以下方式更改内容类型标头:
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded")