{
和}
。这些属性及其值通常称为“键值对”。但是,API传输的JSON以bytes
形式发送,应用程序将其作为string
接收。这些可以转换为JavaScript对象,但默认情况下它们不是JavaScript对象。 JSON.parse
方法解析字符串并构造它描述的JavaScript对象。您可以从freeCodeCamp的Cat Photo API请求JSON。以下是您可以在点击事件中添加的代码: req = new XMLHttpRequest();这是对每件作品的评论。 JavaScript
req.open( “GET”, '/ JSON / cats.json',TRUE);
req.send();
req.onload =函数(){
JSON = JSON.parse(req.responseText);
document.getElementsByClassName( '信息')[0] = .innerHTML JSON.stringify(JSON);
};
XMLHttpRequest
对象具有许多用于传输数据的属性和方法。首先,创建XMLHttpRequest
对象的实例并将其保存在req
变量中。接下来, open
方法初始化一个请求 - 这个例子是从API请求数据,因此是一个“GET”请求。 open
的第二个参数是您从中请求数据的API的URL。第三个参数是布尔值,其中true
使其成为异步请求。 send
方法发送请求。最后, onload
事件处理程序解析返回的数据并应用JSON.stringify
方法将JavaScript对象转换为字符串。然后将此字符串作为消息文本插入。 XMLHttpRequest
。
testString: 'assert(code.match(/new\s+?XMLHttpRequest\(\s*?\)/g), "Your code should create a new XMLHttpRequest
.");'
- text: 您的代码应该使用open
方法初始化对freeCodeCamp Cat Photo API的“GET”请求。
testString: 'assert(code.match(/\.open\(\s*?("|")GET\1\s*?,\s*?("|")\/json\/cats\.json\2\s*?,\s*?true\s*?\)/g), "Your code should use the open
method to initialize a "GET" request to the freeCodeCamp Cat Photo API.");'
- text: 您的代码应使用send
方法发送请求。
testString: 'assert(code.match(/\.send\(\s*\)/g), "Your code should use the send
method to send the request.");'
- text: 您的代码应该有一个设置为函数的onload
事件处理程序。
testString: 'assert(code.match(/\.onload\s*=\s*function\(\s*?\)\s*?{/g), "Your code should have an onload
event handler set to a function.");'
- text: 您的代码应该使用JSON.parse
方法来解析responseText
。
testString: 'assert(code.match(/JSON\.parse\(.*\.responseText\)/g), "Your code should use the JSON.parse
method to parse the responseText
.");'
- text: 您的代码应该获取带有类message
的元素,并将其内部HTML更改为JSON数据字符串。
testString: 'assert(code.match(/document\.getElementsByClassName\(\s*?("|")message\1\s*?\)\[0\]\.innerHTML\s*?=\s*?JSON\.stringify\(.+?\)/g), "Your code should get the element with class message
and change its inner HTML to the string of JSON data.");'
```
```