問題描述
我無法將 XHR responseType 設置為json".如果我將其保留為空字符串 xml.responseType = "";
會正常工作,但是當我將其設置為json"時,我會收到控制臺錯誤消息 SYNTAX_ERR: DOM Exception 12.
I am having trouble setting the XHR responseType to "json". It works fine if I leave it an empty string xml.responseType = "";
but when I set it to "json" I get the console error message SYNTAX_ERR: DOM Exception 12.
.js 文件:
var xml = new XMLHttpRequest();
xml.open("GET", "test.php", true);
xml.responseType = "json";
xml.send();
.php 文件:
<?php
$foo = "{"key1":"val1", "key2":"val2"}";
echo $foo;
?>
不知道發生了什么……有什么想法嗎?
Not sure what's going on.. Any ideas?
推薦答案
responseType
對象的 XMLHttpRequest
屬性已添加到其新變體 XMLHttpRequest Level 2 并且包含在 HTML 5
中,我不確定所有瀏覽器都支持這種方法,所以您使用的瀏覽器可能沒有實現該方法
responseType
property for XMLHttpRequest
object is added in its new variant XMLHttpRequest Level 2 and which is included in HTML 5
, i am not sure all browsers support this method so it could be possible that you are using a browser which doesn't implement that method
您可以使用以下代碼來獲取所需格式的數據,而不是使用 responseType
instead of using responseType
you can use following code to get data in desired format
var xml = new XMLHttpRequest();
xml.open("GET", "test.php", true);
xml.onreadystatechange = function() {
if (xml.readyState != 4) { return; }
var serverResponse = JSON.parse(xml.responseText);
};
xml.send(null);
這篇關于XMLHttpRequest responseType = "json";給出錯誤 SYNTAX_ERR: DOM Exception 12的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!