官方关于这个参数的解释:
Intelligent Guess (xml, json, script, or html)
)- "xml": Returns a XML document that can be processed via jQuery.
- "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
- "script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the
cache
option is set totrue
. Note: This will turn POSTs into GETs for remote-domain requests. - "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
- "jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the
cache
option is set totrue
. - "text": A plain text string.
- multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml." Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.
php文件如下:
<?php
header("Content-Type:text/html;charset=utf-8");
echo json_encode(array("hello","world");
?>
$.ajax({
url:"lib3/grabBaiduBaike.php",
type:"GET",
data:{q:queryValue},
error: function(){
alert('载入数据失败,服务器可能遇到故障');
},
beforeSend:loading,
success:function(data){
console.log(data);
var str1=data[0];
var str2=data[1];
console.log(typeof data);
console.log(str1);
console.log(str2);
}
});
你会发现str1是h,str2为e,与想象的结果不符,这是为什么。
因为php的header中已经说明这是text/html类型,jquery把返回过来的数据就当做字符串串来处理了,加上:
dataType:'json',
就正常了。