原生JS的AJAX請求
//第一步,建立XMLHttpRequest對象
var xhr= new XMLHttpRequest();
function CommentAll() {
//第二步,注冊回調函數
xhr.onreadystatechange =callback1;
//{
// if (xhr.readyState == 4)
// if (xhr.status == 200) {
// var responseText = xmlHttp.responseText;
// }
//}
//第三步,配置請求資訊,open(),get
//get請求下參數加在url後,.ashx?methodName = GetAllComment&str1=str1&str2=str2
xhr.open("post", "/ashx/myzhuye/Detail.ashx?methodName=GetAllComment", true);
//post請求下需要配置請求頭資訊
//xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//第四步,發送請求,post請求下,要傳遞的參數放這
xhr.send("methodName = GetAllComment&str1=str1&str2=str2");//"
}
//第五步,建立回調函數
function callback1() {
if (xhr.readyState == 4)
if (xhr.status == 200) {
//取得傳回的資料
var data = xhr.responseText;
//json字元串轉為json格式
data = eval(data);
$.each(data,
function(i, v) {
alert(v);
});
}
}
<script>
function LoadAjax(){
var date1 = new Date();
var xmlhttpre;
if(window.XMLHttpRequest){
xmlhttpre = new XMLHttpRequest();
}else{
xmlhttpre = new ActiveXObject("Microsoft.XMLHTTP")
}
xmlhttpre.open("get","http://192.168.137.1:8080/h717/allStk",true)
// xmlhttpre.open("post", "http://192.168.62.151:8081/login", true)
// xmlhttpre.setRequestHeader("Content-type","application/x-www-form-urlencoded")
xmlhttpre.send()
xmlhttpre.onreadystatechange=function(){
if(xmlhttpre.readyState==4 && xmlhttpre.status==200){
console.log(xmlhttpre)
console.log(xmlhttpre.responseText);
var result = JSON.parse(xmlhttpre.responseText)
console.log(result)
}
}
}
</script>
<button onclick="LoadAjax();">點選發送請求</button>
jQ的AJAX請求
$(function () {
//點選按鈕 發送ajax請求
$("#btn").on("click", function () {
//發送get請求
$.get("http://127.0.0.1:8080/h717/allStk", function (res) {
// console.log(res) 測試請求是否成功
var jsonObj = eval("(" + res + ")") //把文本轉化成對象
// console.log(jsonObj) 測試資料是否成功轉化成數組對象
if (jsonObj != 'fail') {
$.each(jsonObj, function (i, v) {
console.log(v.stkcode) 拿到所有股票代碼
})
} else {
alert("資料接口異常,請檢查接口配置")
}
})
})
部分參考:https://blog.csdn.net/yh12346789/article/details/79271812