php返回的数据为什么不能直接使用,而要使用这样的形式:
var result = xmlHttp.responseText;
var json = eval("(" + result + ")"); 即要在返回的字符串两边加括号之后才能使用?PS:php端使用json_encode
var result = xmlHttp.responseText;
var json = eval("(" + result + ")"); 即要在返回的字符串两边加括号之后才能使用?PS:php端使用json_encode
{a:'a',b:'b'} // a: 为认为是一个标签,但是后面的,会认为标签没有语法错误{a:'a'} // 不会报错,会认是这样 a:{'a'} 一个标签带一个直接量'a', 表达式内容是'a'会报一个错误,错误的标签而这个就不会有错误
var o = {a:'a',b:'b'}; // 因为是赋值语句,不存在代码块的含义({a:'a',b:'b'}); // 强制转换为语句表达式,不存在代码块的含义
// jquery 返回结果的处理
if ( status === "success" ) {
// Watch for, and catch, XML document parse errors
try {
// process the data (runs the xml through httpData regardless of callback)
// 调用了jQuery.httpData的函数
data = jQuery.httpData( xhr, s.dataType, s );
} catch(err) {
status = "parsererror";
errMsg = err;
}
}
// jQuery.httpData函数
httpData: function( xhr, type, s ) {
var ct = xhr.getResponseHeader("content-type") || "",
xml = type === "xml" || !type && ct.indexOf("xml") >= 0,
data = xml ? xhr.responseXML : xhr.responseText; if ( xml && data.documentElement.nodeName === "parsererror" ) {
jQuery.error( "parsererror" );
} // Allow a pre-filtering function to sanitize the response
// s is checked to keep backwards compatibility
if ( s && s.dataFilter ) {
data = s.dataFilter( data, type );
} // The filter can actually parse the response
if ( typeof data === "string" ) {
// Get the JavaScript object, if JSON is used.
// 如果是json格式的话,则用jQuery.parseJSON解析
if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
data = jQuery.parseJSON( data ); // If the type is "script", eval it in global context
} else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
jQuery.globalEval( data );
}
} return data;
},// jQuery.parseJSON
parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
} // Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
// 会格式化一下json
if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
.replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) { // Try to use the native JSON parser first
// 如果定义window.JSON.parse就调用window.JSON.parse
// 没有的话,创建一个匿名函数对象并且运行,和上面说的例子是一样的道理
return window.JSON && window.JSON.parse ?
window.JSON.parse( data ) :
(new Function("return " + data))(); } else {
jQuery.error( "Invalid JSON: " + data );
}
},