XMLHttpRequest 从响应中获取 ID

问题描述 投票:0回答:1

如何从该回复中获取 ID。

"{\"id\": \"9cf049a8-220a-4103-9f84-354276409390\", \"info\": {\"status\": \"Draft\", \"created_by\": \"[email protected]\", \"location\": \"615 Bourbon St New Orleans\", \"order_type\": \"vbim\", \"first_delivered_at\": null, \"created_at\": 1725162699.505495, \"is_scan_order\": true, \"total_scanned_area\": 0.0, \"go2scan\": null, \"external_id\": \"R4ER93\", \"add_info\": \"Extra info\", \"style_template\": null, \"product\": {\"add_ons\": [], \"over_limits\": [], \"package_type\": \"plus\", \"purchasable_add_ons\": [], \"purchasable_package_types\": []}}, \"address\": {\"city\": \"New Orleans\", \"country\": \"United States\", \"full_address\": \"615 Bourbon St,New Orleans,Louisiana,United States\", \"latitude\": 29.958365, \"longitude\": -90.066198, \"number\": \"\", \"postalCode\": \"70130\", \"state\": \"Louisiana\", \"street\": \"615 Bourbon St\", \"suite\": \"\"}, \"delivery_assets\": {\"gla_package\": null, \"listing_floorplans\": null, \"home_report\": null, \"floorplans_3d\": null, \"video_3d\": null, \"cad_files\": null, \"property_data\": null, \"snapshot\": null}}"

这是我的Javascript

var request = new XMLHttpRequest();

request.open('POST', 'https://app.cubi.casa/api/integrate/v3/orders/draft');

request.setRequestHeader('content-type', 'application/json');
request.setRequestHeader('api-key', 'KEY');

request.onreadystatechange = function () {
if (this.readyState === 4) {
console.log('Status:', this.status);
console.log('Headers:', this.getAllResponseHeaders());
console.log('Body:', this.responseText);
}
};

var body = {
'street': '615 Bourbon St',
'suite': '',
'city': 'New Orleans',
'state': 'Louisiana',
'country': 'United States',
'postalCode': '70130',
'info': 'Extra info',
'latitude': 29.958365,
'longitude': -90.066198,
'external_id': 'R4ER93',
'owner_email': 'Email.com',
'package_type': 'plus'
};

request.send(JSON.stringify(body));
javascript xmlhttprequest
1个回答
0
投票

现在我们可以使用 fetch 并在任何情况下获取response.json:

const process = obj => {
  console.log(obj.id)
};

var body = {
'street': '615 Bourbon St',
'suite': '',
'city': 'New Orleans',
'state': 'Louisiana',
'country': 'United States',
'postalCode': '70130',
'info': 'Extra info',
'latitude': 29.958365,
'longitude': -90.066198,
'external_id': 'R4ER93',
'owner_email': 'Email.com',
'package_type': 'plus'
};

fetch('https://app.cubi.casa/api/integrate/v3/orders/draft', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'api-key': 'KEY' // possibly X-API-KEY:
  },
    body: JSON.stringify(body)
  })
  .then(response => response.json())
  .then(object => process(object))
  .catch(error => console.error(error));
© www.soinside.com 2019 - 2024. All rights reserved.