jQuery는 AJAX 쿼리에서 내 JSON을 구문 분석하지 않습니다.
jQuery.ajax ()를 사용하여 서버에서 반환 된 일부 JSON 데이터를 구문 분석하는 데 어려움이 있습니다.
AJAX를 수행하려면 다음을 사용합니다.
$.ajax({
url: myUrl,
cache: false,
dataType: "json",
success: function(data){
...
},
error: function(e, xhr){
...
}
});
그리고 항목 배열을 반환하면 제대로 작동합니다.
[ { title: "One", key: "1" }, { title: "Two", key: "2" } ]
성공 함수가 호출되고 올바른 개체를받습니다.
그러나 단일 객체를 반환하려고 할 때 :
{ title: "One", key: "1" }
오류 함수가 호출되고 xhr에 'parsererror'가 포함됩니다. JSON을 전송하기 전에 서버에서 괄호로 묶어 보았지만 아무런 차이가 없습니다. 그러나 내용을 Javascript의 문자열에 붙여 넣은 다음 eval () 함수를 사용하면 완벽하게 평가됩니다.
내가 뭘 잘못하고 있는지 아이디어가 있습니까?
안토니
서버가 데이터를 Content-Type으로 보내고 "*/json"
있습니까? 그렇지 않은 경우 응답 헤더를 적절히 수정하십시오. "application/json"
예를 들어 보내기 는 괜찮습니다.
json.org 사양 에 따르면 반품이 유효하지 않습니다. 이름은 항상 따옴표로 묶여 있으므로 반환해야합니다.
{ "title": "One", "key": "1" }
과
[ { "title": "One", "key": "1" }, { "title": "Two", "key": "2" } ]
그중 하나가 지금 작동한다고 말했기 때문에 이것은 설정에 문제가 아닐 수 있지만 나중에 다른 JSON 파서로 전환해야하는 경우를 대비하여 수정해야합니다.
JSON 문자열은 큰 따옴표로 묶여 있습니다. 작은 따옴표는 유효한 대체물이 아닙니다.
{"who": "Hello World"}
유효하지만 이것은 아닙니다 ...
{'who': 'Hello World'}
OP의 문제는 아니지만 여기에 착륙하는 다른 사람들에게는 주목할 가치가 있다고 생각했습니다.
이 문제는 일반적으로 요청이 잘못된 MIME 유형을 수신했기 때문에 발생합니다. 자신의 컴퓨터에서 개발할 때 자신의 컴퓨터 인 "서버"에서 적절한 MIME 유형을받지 못하는 경우가 있습니다. 브라우저에서 로컬로 저장된 파일을 열어 개발할 때이 문제가 한 번 발생했습니다 (예 : URL은 "c : /project/test.html").
beforeSend 속성을 사용하여 MIME 유형을 재정의하는 콜백 함수를 추가해보십시오. 이것은 잘못된 MIME 유형이 서버에서 전송되고 호출 코드에서 수신 되었음에도 불구하고 코드가 json을 처리하도록 속일 것입니다. 몇 가지 예제 코드는 다음과 같습니다.
이 질문 에 따르면 적절한 MIME 유형은 application / json 이지만 시도했을 때 application / j-son이 작동했다는 것을 알고 있습니다 (현재 몇 년 전). 아마도 application / json을 먼저 시도해야합니다.
var jsonMimeType = "application/json;charset=UTF-8";
$.ajax({
type: "GET",
url: myURL,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType(jsonMimeType);
}
},
dataType: "json",
success: function(data){
// do stuff...
}
});
I had this issue and for a bit I used
eval('('+data+')')
to get the data returned in an object. but then later had other issues getting a 'missing ) in parenthetical' error and found out that jQuery has a function specifically for evaluating a string for a json structure:
$.parseJSON(data)
should do the trick. This is in addition to having your json string in the proper format of course..
If you are echoing out the json response and your headers don't match */json then you can use the built in jQuery.parseJSON api to parse the response.
response = '{"name":"John"}';
var obj = jQuery.parseJSON(response);
alert( obj.name === "John" );
{ title: "One", key: "1" }
Is not what you think. As an expression, it's an Object literal, but as a statement, it's:
{ // new block
title: // define a label called 'title' for goto statements
"One", // statement: the start of an expression which will be ignored
key: // ...er, what? you can't have a goto label in the middle of an expression
// ERROR
Unfortunately eval() does not give you a way to specify whether you are giving it a statement or an expression, and it tends to guess wrong.
The usual solution is indeed to wrap anything in parentheses before sending it to the eval() function. You say you've tried that on the server... clearly somehow that isn't getting through. It should be waterproof to say on the client end, whatever is receiving the XMLHttpRequest response:
eval('('+responseText+')');
instead of:
eval(responseText);
as long as the response is really an expression not a statement. (eg. it doesn't have multiple, semicolon-or-newline-separated clauses.)
You will to have to set header content type in your php like this:
<?php
header('Content-type:application/json');
?>
Watch these Video for better understanding....
Reference: http://www.youtube.com/watch?v=EvFXWqEqh6o
If you are consuming ASP.NET Web Services using jQuery, make sure you have the following included in your web.config:
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
I had a similar problem to this where Firefox 3.5 worked fine and parsed my JSON data but Firefox 3.0.6 returned a parseerror. Turned out it was a blank space at the start of the JSON that caused Firefox 3.0.6 to throw an error. Removing the blank space fixed it
The techniques "eval()" and "JSON.parse()" use mutually exclusive formats.
- With "eval()" parenthesis are required.
- With "JSON.parse()" parenthesis are forbidden.
Beware, there are "stringify()" functions that produce "eval" format. For ajax, you should use only the JSON format.
While "eval" incorporates the entire JavaScript language, JSON uses only a tiny subset of the language. Among the constructs in the JavaScript language that "eval" must recognize is the "Block statement" (a.k.a. "compound statement"); which is a pair or curly braces "{}" with some statements inside. But curly braces are also used in the syntax of object literals. The interpretation is differentiated by the context in which the code appears. Something might look like an object literal to you, but "eval" will see it as a compound statement.
In the JavaScript language, object literals occur to the right of an assignment.
var myObj = { ...some..code..here... };
Object literals don't occur on their own.
{ ...some..code..here... } // this looks like a compound statement
Going back to the OP's original question, asked in 2008, he inquired why the following fails in "eval()":
{ title: "One", key: "1" }
The answer is that it looks like a compound statement. To convert it into an object, you must put it into a context where a compound statement is impossible. That is done by putting parenthesis around it
( { title: "One", key: "1" } ) // not a compound statment, so must be object literal
The OP also asked why a similar statement did successfully eval:
[ { title: "One", key: "1" }, { title: "Two", key: "2" } ]
The same answer applies -- the curly braces are in a context where a compound statement is impossible. This is an array context, "[...]
", and arrays can contain objects, but they cannot contain statements.
Unlike "eval()", JSON is very limited in its capabilities. The limitation is intentional. The designer of JSON intended a minimalist subset of JavaScript, using only syntax that could appear on the right hand side of an assignment. So if you have some code that correctly parses in JSON...
var myVar = JSON.parse("...some...code...here...");
...that implies it will also legally parse on the right hand side of an assignment, like this..
var myVar = ...some..code..here... ;
But that is not the only restriction on JSON. The BNF language specification for JSON is very simple. For example, it does not allow for the use of single quotes to indicate strings (like JavaScript and Perl do) and it does not have a way to express a single character as a byte (like 'C' does). Unfortunately, it also does not allow comments (which would be really nice when creating configuration files). The upside of all those limitations is that parsing JSON is fast and offers no opportunity for code injection (a security threat).
Because of these limitations, JSON has no use for parenthesis. Consequently, a parenthesis in a JSON string is an illegal character.
Always use JSON format with ajax, for the following reasons:
- A typical ajax pipeline will be configured for JSON.
- The use of "eval()" will be criticised as a security risk.
As an example of an ajax pipeline, consider a program that involves a Node server and a jQuery client. The client program uses a jQuery call having the form $.ajax({dataType:'json',...etc.});
. JQuery creates a jqXHR object for later use, then packages and sends the associated request. The server accepts the request, processes it, and then is ready to respond. The server program will call the method res.json(data)
to package and send the response. Back at the client side, jQuery accepts the response, consults the associated jqXHR object, and processes the JSON formatted data. This all works without any need for manual data conversion. The response involves no explicit call to JSON.stringify() on the Node server, and no explicit call to JSON.parse() on the client; that's all handled for you.
The use of "eval" is associated with code injection security risks. You might think there is no way that can happen, but hackers can get quite creative. Also, "eval" is problematic for Javascript optimization.
If you do find yourself using a using a "stringify()" function, be aware that some functions with that name will create strings that are compatible with "eval" and not with JSON. For example, in Node, the following gives you function that creates strings in "eval" compatible format:
var stringify = require('node-stringify'); // generates eval() format
This can be useful, but unless you have a specific need, it's probably not what you want.
If returning an array works and returning a single object doesn't, you might also try returning your single object as an array containing that single object:
[ { title: "One", key: "1" } ]
that way you are returning a consistent data structure, an array of objects, no matter the data payload.
i see that you've tried wrapping your single object in "parenthesis", and suggest this with example because of course JavaScript treats [ .. ] differently than ( .. )
If jQuery's error handler is being called and the XHR object contains "parser error", that's probably a parser error coming back from the server.
Is your multiple result scenario when you call the service without a parameter, but it's breaking when you try to supply a parameter to retrieve the single record?
What backend are you returning this from?
On ASMX services, for example, that's often the case when parameters are supplied to jQuery as a JSON object instead of a JSON string. If you provide jQuery an actual JSON object for its "data" parameter, it will serialize that into standard & delimited k,v pairs instead of sending it as JSON.
I found in some of my implementations I had to add:
obj = new Object; obj = (data.obj);
which seemed to solve the problem. Eval or not it seemed to do exactly the same for me.
jQuery chokes on certain JSON keys. I was sending this JSON snippet in PHP:
echo json_encode((object) array('result' => 'success'));
Renaming the 'result' key to something else works. I would guess this is a reserved word collision of some kind, and could be a bug in jQuery (1.4.2).
In a ColdFusion environment, one thing that will cause an error, even with well-formed JSON, is having Enable Request Debugging Output turned on in the ColdFusion Administrator (under Debugging & Logging > Debug Output Settings). Debugging information will be returned with the JSON data and will thus make it invalid.
also try this
$.ajax({
url: url,
data:datas,
success:function(datas, textStatus, jqXHR){
var returnedData = jQuery.parseJSON(datas.substr(datas.indexOf('{')));
})};
in my case server responds with unknow character before '{'
I was getting status = parseerror and xhr.status = 200.
The issue for me was the URL's inside the JSON response had '\' switching to '/' fixed this.
I was struggling with this, and spent a few hours trying to figure this out, until I used firebug to show the data object.
var data = eval("(" + data.responseText + ")");
console.log(data.count);
use
$data = yourarray();
json_encode($data)
on server side. On client side use ajax with Datatype JSON and be sure your document encoding is not UTF-8 with BOM it has to be UTF-8.
참고URL : https://stackoverflow.com/questions/249692/jquery-wont-parse-my-json-from-ajax-query
'developer tip' 카테고리의 다른 글
Twitter Bootstrap을 사용하여 테이블 셀에서 세로로 버튼 중앙에 배치 (0) | 2020.09.11 |
---|---|
CONDITIONS가있는 COUNT DISTINCT (0) | 2020.09.11 |
좋은 프로그래머의 코드는 어떤 모습일까요? (0) | 2020.09.10 |
EditText의 setHintTextColor () (0) | 2020.09.10 |
Java에서 날짜가 두 날짜 사이에 있는지 어떻게 확인할 수 있습니까? (0) | 2020.09.10 |