美文网首页
AJAX 扩展 异步请求数据的几种方法-jquery篇

AJAX 扩展 异步请求数据的几种方法-jquery篇

作者: 起个名字太费劲 | 来源:发表于2017-08-24 13:03 被阅读0次

1.jquery的 load(url,data,function(response,status,xmlHttp)) url :请求的服务器地址 ,data(向服务器传递的参数:1-》get传值,直接在url上拼接需要传递的参数此时data参数不需要,服务器那边用$_GET取值,2-》post传值,在data里传递一个json的数据类型{one:"one",two:"two"}) function 异步函数当从服务器返回json(此时的 json数据时string类型,使用需要转换称json结构类型,JSON.parse())

load get 传值
前端:
$(function(){
var odiv = $("#odiv");//div,将返回的数据显示在div中
var ousername = $("#username");//输入框
var otxt = $("#txt");// 文本输入框
var obtn = $("#obtn");//提交按钮
obtn.click(function () {

// $(this).load("server.php?username="+ousername.val()+"&txt="+otxt.val(),// 此时直接将需要传递的参数直接拼接在url上,data数据不需要设置
// function(responseText,status,xmlHttp){
// console.log(responseText);
//// console.log(typeof(JSON.parse(responseText)));
//// console.log(status);
//// console.log( typeof(xmlHttp.responseText));
// });

            })

服务器:
<?php
$username = $_GET['username'];
$txt = $_GET['txt'];
$arr[] = $username;
$arr[] = $txt;
echo json_encode($arr);
load post传值
前端:
$(function(){
var odiv = $("#odiv");
var ousername = $("#username");
var otxt = $("#txt");
var obtn = $("#obtn");
obtn.click(function () {

                     $(this).load("server.php",{username:"lpf",txt:"11"},//此时将需要传递的参数以json格式作为data的参数传递
                    function(responseText,status,xmlHttp){
                        console.log(responseText);

// console.log(typeof(JSON.parse(responseText)));
// console.log(status);
// console.log( typeof(xmlHttp.responseText));
});
});

            })

服务器端:
<?php
$username = $_POST['username'];
$txt = $_POST['txt'];
$arr[] = $username;
$arr[] = $txt;
echo json_encode($arr);

2.  $.get(url,data,function(response,status,xmlhttp),dataType) 

          $.post(url,data,function(response,status,xmlhttp),dataType)

$.get和 $.post分别以get和post方式发送异步请求和load函数的差别在于最后独创的dataType的区别 dataType指的是服务器返回的数据,然后将其转换称dataType的数据类型

* dataType的指有
* "xml"、//   typeof(response)=xml
* "html"//   typeof(response)=html
* "text"//   typeof(response)=text
* "script"//   typeof(response)=script
* "json"//   typeof(response)=json//最常用
* "jsonp"//   typeof(response)=jsonp

3.ajax
$.ajax({
url: 'shoppingcart.php?a=addshopingcart',
type: 'post',
data: {'id': $("#id").val(), 'buynum': $("#buynum").val()},
dataType: 'html',// 返回值类型可以是text json html ,选择json时返回来的数据就是json格式的数据就不需要进行json转换了
success: function (data) {
if (a == "buy") {
location.href = "shoppingcart.php?a=buynow";
} else {
alert(data);
}
}
});

相关文章

网友评论

      本文标题:AJAX 扩展 异步请求数据的几种方法-jquery篇

      本文链接:https://www.haomeiwen.com/subject/yytedxtx.html