jquery Ajax Return Data Exception resolution method

Source: Internet
Author: User
Tags error code json

New station's message board added a penthouse function, do not know you have used it?

In the beginning, I did not appear in the test when the problem, the specific questions below analysis, here first grumble.

Tonight, idle boring, and thinking about the previous days found that the message board IP transfer Physical Address invalid problem, so open the site point. Only to point out the problem:

After the top, the page wood has any response, refresh the page after the top of the operation is indeed successful implementation.

Initial analysis, this is definitely Ajax return, JS Wood has a normal interaction caused.

Turned on chrome and found that the Ajax return was successful, but the return value was odd, as follows

Http_raw_post_data = SUCCESS

Theoretically, successful execution requires returning SUCCESS, how does this return a http_raw_post_data = SUCCESS? Puzzled. Adjust the PHP page return method is useless, decisive and the problem boils down to JS.

See, other similar JS request, found that the return value is normal SUCCESS, only our top brother appears this anomaly.

What's a Google Http_raw_post_data to start with? Probably understand the next, basically is PHP to non-standard (for PHP itself) POST data format, you can take value from Http_raw_post_data here, specific to google it yourself.

A bit of a clue, it is estimated that the request is a problem, under the unmodified code fragment:

The code is as follows Copy Code

$.ajax ({
Type: "Post",
URL: "index.php?m=request&do=upmessage&id=" + ID + "&rdn=" +math.random (),
DataType: "Text",
Success:function (d) {
Switch ($.trim (d)) {
Case "ERROR":
Alert ("Zennai character is really not good, wrong ...");
Break
Case "SUCCESS":
$ ("#up_num_" +id). HTML (parseint ($ ("#up_num_" +id). HTML ()) +1);
O.setattribute ("onclick", "javascript:void (0);");
O.style.color = "#666";
Break
Default
Break
}
},
Error:function (XMLHttpRequest, Textstatus, Errorthrown) {
alert (Errorthrown);
}
});


What's the doorway to the wood?

In fact, at the beginning I did not see what dongdong come, ashamed ...

The code is as follows Copy Code

Type: "Post",
URL: "index.php?m=request&do=upmessage&id=" + ID + "&rdn=" +math.random (),


Split into

Type: "Post",
URL: "index.php?m=request&do=upmessage&rdn=" +math.random (),
Data: "id=" + ID,


OR

Type: "Get",
URL: "index.php?m=request&do=upmessage&id=" + ID + "&rdn=" +math.random (),


That 's it, that's why.

In fact, using the Ajax method in jquery to make the request, if the request method is post then you have to post a non-empty data parameter, otherwise you will report the above error! Because, all post data is not so should be random post data, I this is nonsense to say, probably this meaning, deep reason own Google it, I this point to this, but then I if use Chinese again encounter problem, Chinese return for garbled, Here oneself do not take up to change the direct find a solution to everyone.

Ajax return value is Chinese when garbled

The code is as follows Copy Code

Server-side code:
/**
* Asynchronous (returns JSON data format) (support paging)
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws appexception
*/
Public Actionforward queryerrorcoderecordbypage (actionmapping mapping, Actionform form,
HttpServletRequest request, HttpServletResponse response) {

Integer currentpage = Integer.parseint (Request.getparameter ("currentpage"));
Integer pagesize = Integer.parseint (Request.getparameter ("pagesize"));
Try
{
List listbypage = This.errorCodeRecordFacade.queryErrorCodeRecordByPage (CurrentPage, pagesize);
Jsonarray json = Jsonarray.fromobject (listbypage);
System.out.println ("Jsonarray Data---" + json.tostring ());

Request.setcharacterencoding ("Utf-8"); There's no code here.
Response.setcontenttype ("Text/html;charset=utf-8");
Response.setheader ("Cache-control", "No-cache");
PrintWriter out = Response.getwriter (); Output Chinese, this sentence must be put to Response.setcontenttype ("Text/html;charset=utf-8"), Response.setheader ("Cache-control", "No-cache ") back, otherwise Chinese returned to the page is garbled
Out.print (Json.tostring ());
Out.flush ();
Out.close ();
}
catch (Exception e) {
Log.error ("Query data Error", E);
}
return null;
}


Client's code:

The code is as follows Copy Code

Asynchronously takes error code history data based on pagination
function Search_errorcoderecord (currentpage,pagesize)
{
$.ajax ({
Async:true,
URL: "<%=request.getcontextpath ()%>/errorcoderecord/queryerrorcoderecordbypage.do",
Type: "Post",
Data: {currentpage:currentpage, pagesize:pagesize},
DataType: "JSON",//The data format has been defined here
ContentType: "application/x-www-form-urlencoded; Charset=utf-8 ",
Success:function (data) {
alert (data);
var json=eval (' (' +data+ ') '); The jquery call is detected so that the return format is processed directly as JSON, so the conversion will be an error.
var json=eval (data);
Resolv_json (JSON);
}
});
}


Parse JSON array, dynamically stitch into white div
function Resolv_json (JSON)
{
for (Var i=0;i<json.length;i++)
{
alert (json[i].boss_resultinfo);

var operate_state = "new";
if (json[i].operate_state = = "2")
{
Operate_state= "Modified";
}
if (json[i].operate_state = = "3")
{
operate_state= "deleted";
}

var p=$ ("<p></p>");
var span1=$ ("<span></span>");
var span2=$ ("<span></span>");
var span3=$ ("<span></span>");
var span4=$ ("<span></span>");

var times = Json[i].operate_time.time;
alert (json[i].operate_time.time); Time format is a JSON object
alert (getlocaltime);
Span1.html (Getlocaltime (times));
Span2.html (json[i].operate_people);
Span3.html (operate_state);
span4.html (json[i].businessname + "error code");

P.append (Span1). Append (span2). Append (SPAN3). Append (SPAN4);
$ ("#whiteDiv"). Append (P);
}

}

Time Stamp converted to time
function Getlocaltime (NS) {
return new Date (parseint (NS)). toLocaleString (). Replace (/:d {1,2}$/, ");
}


<div id= "Whitediv" >

</div>

Summarized as follows:

1. PrintWriter out = Response.getwriter (); Be sure to put it in

Request.setcharacterencoding ("Utf-8"); Response.setcontenttype ("Text/html;charset=utf-8");

The back of the code (the reason is very simple, you know.) )


2. jquery plus Content-type parameters are not affected.

ContentType: "application/x-www-form-urlencoded; Charset=utf-8 ",

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.