jQuery Ajax POST请求 - 响应文本为空并且状态为Firefox中的400 Bad Request

时间:2013-10-24 10:15:21

标签: jquery ajax json post

我有以下jQuery AJAX请求:

function addRecord() {    
    console.log('addRecord');
    $.ajax({
        type: 'POST',        
        url: rootURL,
        contentType: 'application/json',
        dataType: "json",
        data: formToJSON(),        
        success: function(data, textStatus, jqXHR){
            alert('form submitted successfully');            
            alert('data'+data);
        },
        error: function (xhRequest, ErrorText, thrownError) {
            alert("Failed to process request correctly, please try again");

            console.log('xhRequest: ' + xhRequest + "\n");
            console.log('ErrorText: ' + ErrorText + "\n");
            console.log('thrownError: ' + thrownError + "\n");
        }
    });
}

function formToJSON() {
return JSON.stringify({"dateofVisit": $('#dateofVisit').val()}); 
}

以下是我在firebug中收到的输出。

响应标头:

Server  Apache-Coyote/1.1
Access-Control-Allow-Orig...    *
Access-Control-Allow-Cred...    true
Access-Control-Allow-Meth...    GET, POST, DELETE, PUT, OPTIONS, HEAD
Access-Control-Allow-Head...    Content-Type, Accept, X-Requested-With
Content-Type    text/plain
Transfer-Encoding   chunked
Date    Thu, 24 Oct 2013 09:37:34 GMT
Connection  close
Request Headersview source
Host    localhost:8080
User-Agent  Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.10) Gecko/20100914 Firefox/3.6.10
Accept  application/json, text/javascript, */*; q=0.01
Accept-Language en-us,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
Referer http://mydomain.com/DemoPurpose/demo.html
Content-Length  28
Origin  http://mydomain.com
Pragma  no-cache
Cache-Control   no-cache

POST:

JSON    
dateofVisit
    "23-10-2013"
Source
{"dateofVisit":"23-10-2013"}

响应:

empty

控制台输出:

xhRequest: [object Object]
ErrorText: error
thrownError: 

我是jquery的新手,所以基本上不知道我在做错误的地方。有一件事是肯定它会出现ajax调用的错误,但为什么呢?它能够形成json ...然后它为什么会出错?请帮帮我。

1 个答案:

答案 0 :(得分:2)

来自jquery doc

当你放dataType=json时,这意味着你不应该返回空内容。

“json”:将响应评估为JSON并返回JavaScript对象。 JSON数据以严格的方式解析;任何格式错误的JSON都会被拒绝,并抛出一个解析错误。从jQuery 1.9开始,空响应也被拒绝;服务器应该返回null或{}的响应。 (有关正确的JSON格式的更多信息,请参阅json.org。)

此外,您需要检查您的回复状态是200还是400。

您的服务器端代码存在一些问题

@POST @Consumes({MediaType.APPLICATION_JSON}) 
@Produces({MediaType.TEXT_PLAIN}) @Path("/hello") 
//---------------------^^^ why you use plain text? why not application json
public Response create(String name) throws JSONException
{
 System.out.println("creating record for account");
 //JSONObject jsonObj = new JSONObject(name);
 //------------------------------^^^^^ it's not jsonformat, error should be here
 //try this way
 JSONObject jsonObj = new JSONObject();
 jsonObj.append("name",name);
 return Response.status(201).entity(jsonObj).build();
}