我正在尝试使用
XMLHttpRequest对象从表单发送
JSON数据.我可以使用以下函数发送数据. FireBug中没有显示错误,请求中的JSON数据显示为FireBug.
POST数组始终为空,但我可以看到file_get_contents返回的JSON字符串.这是怎么发生的?我究竟做错了什么?
- 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
- }