简体   繁体   English

如何使用 JavaScript Fetch 发送和接收数据

[英]How to send and receive data using JavaScript Fetch

I am trying to make a request to an external page in JS and return the data.我正在尝试向 JS 中的外部页面发出请求并返回数据。 This will need to await a response so using AJAX I dont think will work but I may be mistaken.这将需要等待响应,因此我认为使用 AJAX 行不通,但我可能会误会。 I am not well versed in JS so forgive me if im way off here just trying to learn.我不太精通 JS,所以如果我只是想学习,请原谅我。

Here is the request script -这是请求脚本 -

fetch('return.php', { 
    method: 'GET'
 })
 .then(function(response) { return response.json(); })
 .then(function(json) {
     obj = JSON.parse(text);
     document.getElementById("demo").innerHTML = obj.employees[1].firstName + " " + 
     obj.employees[1].lastName;
 });

Then I have a JSON response in the return file -然后我在返回文件中有一个 JSON 响应 -

var text = '{"employees":[' +
    '{"firstName":"John","lastName":"Doe" },' +
    '{"firstName":"Anna","lastName":"Smith" },' +
    '{"firstName":"Peter","lastName":"Jones" }]}';

Everytime I try and execute this I get每次我尝试执行此操作时,我都会得到

Unexpected token < in JSON at position 0

Which I believe means it is not returning JSON data but I may be wrong.我相信这意味着它没有返回 JSON 数据,但我可能错了。 How can I make a request to the return page and return data when its finished with the function execution.如何在函数执行完成后向返回页面发出请求并返回数据。

Thanks!谢谢!

Unexpected token < in JSON at position 0 strongly implies that return.php is returning html of some kind. Unexpected token < in JSON at position 0强烈暗示 return.php 正在返回某种类型的 html。 Try navigating to return.php to see what it's returning, and then parse accordingly.尝试导航到 return.php 以查看它返回的内容,然后进行相应的解析。

You do not need obj = JSON.parse(text);你不需要obj = JSON.parse(text); . . This will throw an error as text is not defined, but your fetch call is failing on response.json(), as the response is not json.由于文本未定义,这将引发错误,但您的 fetch 调用在 response.json() 上失败,因为响应不是 json。

maybe this fixes things?也许这可以解决问题? :

fetch('return.php', {
  method: 'GET',
})
  .then((response) => {
    response.json();
  })
  .then((jsonResponse) => {
    const obj = jsonResponse;
    document.getElementById('demo').innerHTML =
      obj.employees[1].firstName + ' ' + obj.employees[1].lastName;
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM