如何使用本机XMLHttpRequest从SPA上的请求输出数据



我有一个条件html页面和一个条件api。

在我的api中获取用户数据的请求如下:

URL: {host}/user
Method: GET
Headers
- Content-Type: application/json
- Authorization: Bearer {token}

回应:

Status: 200
Content-Type: application/json
Body:
{
"first_name": "Ivan",
"last_name": "Ivanov",
"phone": "89001234567",
"document_number": "1224567890"
}

如何使用XMLHttpRequest发送请求并输出响应数据?

我试着使用xhr.response(),它工作得很好,但当我尝试使用xhr.response()['first_name']时,它不能正常工作

如果您有本地JavaScript和jQuery可用的,我会看到两个选项

获取API

或者更老的";标准";jQuery的。

$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});

解决方案非常简单。

xhr.response()的标准输出,其中xhr = new XMLHTTPRequest();不是JSON,所以我需要将xhr.responseType = 'json'放在xhr.open('POST', url)之前

最新更新