Jquery ajax return Data Exception Solution

Source: Internet
Author: User
Tags floor function

Ajax returns a lot of data, which can be called a returned Data Exception. If the returned data is not what I want or is garbled, next I will use an example to introduce some examples of jquery ajax returned data exceptions.

A new top-floor function is added to the message board of the new small station. Do you know if you have used it?

At the beginning, this problem did not appear during the test. The specific problem is analyzed below. Here, I will complain first.

This evening, I was bored and remembered that the IP address to the physical address of the message board I found a few days ago was invalid. So I clicked on the website. This problem occurs unexpectedly:

After clicking the top button, the page wood has any reaction. After refreshing the page, the top operation is indeed successful.

According to the preliminary analysis, this is definitely caused by the normal interaction of js wood.

After chrome is enabled, it is found that the ajax return is successful, but the return value is strange, as shown below:

HTTP_RAW_POST_DATA = SUCCESS

Theoretically, SUCCESS is returned for successful execution. How does one return HTTP_RAW_POST_DATA = SUCCESS? Puzzled. Adjusting the php page return method does not help, and the problem is resolutely attributed to js.

Check it. Other Similar js requests found that the returned values were normal SUCCESS, and this exception only occurred to our top-floor brother.

What was google HTTP_RAW_POST_DATA at the beginning? After learning about it, php basically uses the non-standard (for php) post data format. You can set the value from HTTP_RAW_POST_DATA to google.

A little clue, it is estimated that there is a problem with the request, below is the code segment before the modification:

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 ("donnai's character is really bad, it's 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 do you see?

In fact, I didn't see anything at first...

The Code is as follows: Copy code

Type: "post ",
Url: "index. php? M = request & do = upMessage & id = "+ id +" & rdn = "+ Math. random (),


Split

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 (),


This is the reason.

In fact, the ajax method in jquery is used for the request. If the request method is post, you must post a non-empty data parameter. Otherwise, the above error will be reported! Because not all post data should be post data randomly. I am not talking about it. Maybe that means it. google is the reason for the deep reasons. I am here to point to it, however, if I encountered another problem when using Chinese, the returned Chinese text would be garbled. Here, I did not turn it into a correct one and found a solution for you.

The ajax return value is garbled in Chinese.

The Code is as follows: Copy code

Server code:
/**
* Asynchronous (json data format returned) (pagination supported)
* @ 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"); // garbled characters are not set here.
Response. setContentType ("text/html; charset = UTF-8 ");
Response. setHeader ("Cache-Control", "no-cache ");
PrintWriter out = response. getWriter (); // output Chinese characters. This sentence must be placed in response. setContentType ("text/html; charset = UTF-8"), response. setHeader ("Cache-Control", "no-cache"). Otherwise, garbled characters are returned to the page.
Out. print (json. toString ());
Out. flush ();
Out. close ();
}
Catch (Exception e ){
Log. error ("Data Query error", e );
}
Return null;
}


Client code:

The Code is as follows: Copy code

// Retrieve historical error code data asynchronously Based on paging
Function search_errorCodeRecord (currentpage, pagesize)
{
$. Ajax ({
Async: true,
Url: "<% = request. getContextPath () %>/errorCodeRecord/queryErrorCodeRecordByPage. do ",
Type: "post ",
Data: {currentpage: currentpage, pagesize: pagesize },
// DataType: "json", // data format defined here
ContentType: "application/x-www-form-urlencoded; charset = UTF-8 ",
Success: function (data ){
Alert (data );
// Var json = eval ('+ data +'); // It is detected when jquery is called, and the returned format is treated as json directly, therefore, an error will be reported when conversion is performed.
Var json = eval (data );
Resolv_json (json );
}
});
}
 
 
// Parse the json array and dynamically splice it into a white Div
Function resolv_json (json)
{
For (var I = 0; I <json. length; I ++)
{
// Alert (json [I]. boss_resultinfo );

Var operate_state = "added ";
If (json [I]. operate_state = "2 ")
{
Operate_state = "modified ";
}
If (json [I]. operate_state = "3 ")
{
Operate_state = "deleted ";
}

Var p = $ ("<p> </p> ");
Var span1 =1 ("<span> </span> ");
Var span2 =2 ("<span> </span> ");
Var span3 = $ ("<span> </span> ");
Var span4 =4 ("<span> </span> ");

Var times = json [I]. operate_time.time;
// Alert (json [I]. operate_time.time); // The time format is a JSON object.
// Alert (getLocalTime (times ));
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 );
}
 
}
 
// Convert the timestamp to time
Function getLocalTime (nS ){
Return new Date (parseInt (nS). toLocaleString (). replace (/: d {1, 2} $ /,'');
}


<Div id = "whiteDiv">

</Div>

Summary:

1. PrintWriter out = response. getWriter (); must be placed in

Request. setCharacterEncoding ("UTF-8"); response. setContentType ("text/html; charset = UTF-8 ");

After encoding (The reason is very simple, you know .)


2. jquery parameters without content-type 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.