⑴ 如何用js調用url介面
在javaScript中調用URL介面主要依賴瀏覽器提供的API。常用方法包括XMLHttpRequest、fetch和axios。XMLHttpRequest是用於在瀏覽器中發送HTTP請求的API,適用於GET、POST等請求類型,可非同步接收伺服器返回數據。XMLHttpRequest兼容性好,適用於IE6+、Firefox、Chrome等現代瀏覽器。以下是使用XMLHttpRequest發送GET請求的示例:
XMLHttpRequest示例:
javascript
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
fetch是基於Promise的API,提供簡潔發送HTTP請求方式,非同步接收伺服器返回數據。fetch兼容性較好,適用於現代瀏覽器,但在IE11等老舊瀏覽器中需使用polyfill。以下是使用fetch發送GET請求的示例:fetch示例:
javascript
fetch('https://api.example.com/data')
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.error(error));
axios是一個基於Promise的HTTP客戶端,支持瀏覽器和Node.js環境使用。提供簡潔發送HTTP請求方式,包含自定義攔截器、取消請求等高級功能。axios兼容性好,但需在IE11等老舊瀏覽器中使用polyfill。以下是使用axios發送GET請求的示例:axios示例:
javascript
axios.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => console.error(error));
根據具體業務需求及瀏覽器兼容性情況選擇合適的方法即可。
⑵ HTML js怎麼發送HTTP get請求
請參照下面的例子:
/*URL可以隨意改*/
String uriAPI = "http://192.168.1.100:8080/test/test.jsp?u=wangyi&p=456";
/*建立HTTP Get對象*/
HttpGet httpRequest = new HttpGet(uriAPI);
try
{
/*發送請求並等待響應*/
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
/*若狀態碼為200 ok*/
if(httpResponse.getStatusLine().getStatusCode() == 200)
{
/*讀*/
String strResult = EntityUtils.toString(httpResponse.getEntity());
/*去沒有用的字元*/
strResult = eregi_replace("( | | | )","",strResult);
mTextView1.setText(strResult);
}
else
{
mTextView1.setText("Error Response: "+httpResponse.getStatusLine().toString());
}
}
catch (ClientProtocolException e)
{
mTextView1.setText(e.getMessage().toString());
e.printStackTrace();
}
catch (IOException e)
{
mTextView1.setText(e.getMessage().toString());
e.printStackTrace();
}
catch (Exception e)
{
mTextView1.setText(e.getMessage().toString());
e.printStackTrace();
}
⑶ js image對象可以發送http請求嗎
可以。
首先在html文檔中准備一個區域用來顯示請求返回的內容,並且給onload事件綁定好方法。然後我們建立一個對象。接下來處理xmlhttprequest的onload方法。接下來,調用請求對象的open方法,設置請求的方式為get,並設置請求url。然後調用請求對象的send方法執行請求發送。最後我們來處理一下請求返回成功後,給顯示區域賦值的方法。