Home >Web Front-end >JS Tutorial >Introduction to the get and post methods based on js native and ajax as well as the native writing method of jsonp
The following brings you an example of the get and post methods based on js native and ajax, as well as the native writing method of jsonp. The content is quite good, so I will share it with you now and give it as a reference.
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 method
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 method passing parameters
The difference between it and the get method:
01 Safe type. post is safer.
02 Speed. The speed of get is
03 orders of magnitude faster. The order of magnitude of post is larger.
Specific implementation:
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); }; }; }
Native jsonp method
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); }
The above is the entire content of this article. I hope it will be helpful to everyone’s learning. Please pay attention to more related content. PHP Chinese website!
Related recommendations:
Native implementation of Ajax About the use of MIME types
Write Ajax request function in native JS Function
The correct way to pass ajax callback function parameters
The above is the detailed content of Introduction to the get and post methods based on js native and ajax as well as the native writing method of jsonp. For more information, please follow other related articles on the PHP Chinese website!