首頁 > web前端 > js教程 > 主體

基於js原生和ajax的get和post方法以及jsonp的原生寫法的介紹

不言
發布: 2018-07-02 17:04:50
原創
1890 人瀏覽過

下面為大家帶來一個基於js原生和ajax的get和post方法以及jsonp的原生寫法實例。內容還挺不錯的,現在就分享給大家,也給大家做個參考。

login.onclick = function(){
var xhr = new XMLHttpRequest();
xhr.open("get","http://localhost/ajax2/test2.php?username="+username.value+"&pwd="+pwd2.value,true);
xhr.send();
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
if (xhr.status>=200 && xhr.status<300) {
alert(xhr.responseText);
};
};
}
}
登入後複製

ajax方法

##

btn.onclick = function(){
ajax(
    "GET",
    "http://localhost/ajax2/my02.php",
    {xingming:xingming.value,pwd:pwd.value},
    function(data){
console.log(data);
},
function(errCode){
console.log(errCode);
}
)
登入後複製

post方法傳參

它與個get方法的差異:

01 安全型。 post更安全。

02 速度. get的速度快

03 數量級。 post的數量級更大一些.

具體實作:

#

var xhr = new XMLHttpRequest();
xhr.open("post","http://localhost/ajax2/login2.php",true);
var data = {
username:username1.value,
pwd:pwd1.value
}
// 设置请求头 告诉服务器发给他的数据是json格式
xhr.setRequestHeader("content-type","application/json");
xhr.send( JSON.stringify(data) );
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
if ( xhr.status >= 200 && xhr.status < 300 ) {
alert(xhr.responseText);
};
};
}
登入後複製

##原生jsonp 方法

var sc = document.createElement("script");
sc.type = "text/javascript";
document.body.appendChild(sc);
sc.src = "http://localhost/ajax2/jsonp.php?cb=myCallBack";

function myCallBack(data){
console.log(data);
}
登入後複製

#以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP中文網!

相關推薦:

Ajax的原生實作關於MIME類型的使用方法


原生JS寫Ajax的請求函數功能


ajax回呼函數參數傳遞正確方法


以上是基於js原生和ajax的get和post方法以及jsonp的原生寫法的介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!