gpt-4-0314· openai
Suzhen/CodeChat
Make an HTTP request in JavaScript
- User
Make an HTTP request in JavaScript
- Assistant
You can make an HTTP request in JavaScript using the
fetch()function or the olderXMLHttpRequestobject. Here's an example of both:- Using
fetch()(recommended):
fetch('https://api.example.com/data') .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(data => { console.log(data); }) .catch(error => { console.error('There was a problem with the fetch operation:', error); });- Using
XMLHttpRequest:
const xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 200) { const data = JSON.parse(xhr.responseText); console.log(data); } else { console.error('There was a problem with the request:', xhr.statusText); } } }; xhr.open('GET', 'https://api.example.com/data', true); xhr.send(null);In general,
fetch()is recommended overXMLHttpRequestbecause it is newer, more powerful, and has a more concise syntax with better error handling. However, if you need to support older browsers, you may need to use . - Using
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.