zoukankan      html  css  js  c++  java
  • jQuery中异步请求

    1、load方法

    使用load()方法通过Ajax请求加载服务器中的数据,并把返回的数据放置到指定的元素中,它的调用格式为:

    $(selector).load(URL,data,callback);

    参数url为加载服务器地址,可选项data参数为请求时发送的数据,callback参数为数据请求成功后,执行的回调函数。

    例子:加载phpinfo.php页面并将放回的结果放到<div>中

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>使用load()方法异步请求数据</title>
      <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script>
    </head>
    <body>
    <input id="button" type="button" value="加载"/>
    <div id="test"></div>
    <script type="text/javascript">
    $(document).ready(function(){
      $("#button").click(function(){
        $("#test").load("/phpinfo.php",function(responseTxt,statusTxt,xhr){
          if(statusTxt=="success")
            alert("外部内容加载成功!");
            alert(responseTxt);
          if(statusTxt=="error")
            alert("Error: "+xhr.status+": "+xhr.statusText);
        });
      });
    });
    </script>
    </body>
    </html>

    2.getScript()方法

    使用getScript()方法异步请求并执行服务器中的JavaScript格式的文件,它的调用格式如下所示:

    jQuery.getScript(url,[callback])$.getScript(url,[callback])

    参数url为服务器请求地址,可选项callback参数为请求成功后执行的回调函数。

    ####这个方法就是调用js文件并执行,可以跨域操作#####

    a.html

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script>
    </head>
    <body>
    <input id="button" type="button" value="加载"/>
    <script type="text/javascript">
    $(document).ready(function(){
      $("#button").click(function(){
          $.getScript('http://www.123.com:81/2.js',function(){alert("success")})
      });
    });
    </script>
    </body>
    </html>

    2.js

    alert('2.js加载成功');  调用成功

    执行了回调函数。

    3.通过get方法

    使用get()方法时,采用GET方式向服务器请求数据,并通过方法中回调函数的参数返回请求的数据,它的调用格式如下:

    $.get(url,[callback])

    参数url为服务器请求地址,可选项callback参数为请求成功后执行的回调函数。

    #########不能跨域访问###############

    a.html

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
      <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script>
    </head>
    <body>
    <script type="text/javascript">
    $.get("http://www.123.com/",function(data,status){alert("数据:" + data + "
    状态:" + status)});
    </script>
    </body>
    </html>

    a.html文件

    4.通过post方法

    #######不能给跨域############

    a.html

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
      <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script>
    </head>
    <body>
        <div id="html"></div>
    <script type="text/javascript">
    $.post("http://www.123.com/test.php",
        {
            name:"afanti",
            sex:"man"
        },
        function(data,status){
            alert("数据:" + data + "
    状态:" + status);
            document.getElementById("html").innerHTML = data
        });
    </script>
    </body>
    </html>

    test.php

    5.getJSON

    $.getJSON("/test.php?name=afanti&sex=man").then(
    function(result){
    alert(result.name+result.sex);
    });

    then后面处理回调。getScript也可以使用。

    6.ajax发出请求。a.html

    $.ajax({
        type:"get",
        url:"test.php",
        data:{"name":"afanti","sex":"man"},
        catche: false,
        async: false,
        timeout: 1000,
        dataType:"json",  //预期服务器返回的数据类型。支持参数:xml,html,script,json,text,jsonp
        contentType: 'application/x-www-form-urlencoded',
       headers:{
      "header1":"aaaa" //设置请求头1
    },
       beforeSend:function(xhr){
        xhr.setRequestHeader("header2","bbbb") //设置请求头2
      }
         jsonp:
    'callback', jsonpCallback: 'jsonpCallback',
       //xhrFields:{
       //withCredentials:true //默认情况下,跨域请求不携带cookie。不跨域就可以携带cookie。通过设置这个参数可以实现跨域携带cookie但是后台代码,Access-Contro-Allow-Credentials:true加上这个头部信息
    //} success:
    function(data,status) { document.getElementById("html").innerHTML=data.name+";"+data.sex; // document.getElementById("html").innerHTML=data; alert(status); }, error:function(err,status) { alert(status); } });

    test.php

     ajax实现jsonp

    http://www.123.com/a.html

    $.ajax({
        type:"get",
        url:"http://www.123.com:81/test.php",
        catche: false,
        async: false,
        timeout: 1000,
        dataType:"jsonp",  //预期服务器返回的数据类型。
        contentType: 'application/x-www-form-urlencoded',
        jsonp: 'callback',           //http://www.123.com:81/test.php?callback=callback1111&_=1529803521061发出这样的请求
        jsonpCallback: 'callback1111',        //回调函数的名字
        success:function(data,status)
        {
               for(var key in data)
          {
          console.log(key,data[key]);

          } //1、这里 alert(status); }, error:
    function(err,status) { // alert(status); } }); function callback1111(data) { alert(data); //2、都能获取到数据 }

    www.123.com:81/test.php

    <?php
    $callback = $_GET['callback'];//得到回调函数名
    $data = array('name'=>'afanti','sex'=>'man');//要返回的数据
    echo $callback.'('.json_encode($data).')';//输出
    ?>

    可以进行跨域访问。

    参考文章:

    https://www.xmanblog.net/2018/04/09/web-cross-domain-ecurity/

  • 相关阅读:
    Java RunTime Environment (JRE) or Java Development Kit (JDK) must be available in order to run Eclipse. ......
    UVA 1597 Searching the Web
    UVA 1596 Bug Hunt
    UVA 230 Borrowers
    UVA 221 Urban Elevations
    UVA 814 The Letter Carrier's Rounds
    UVA 207 PGA Tour Prize Money
    UVA 1592 Database
    UVA 540 Team Queue
    UVA 12096 The SetStack Computer
  • 原文地址:https://www.cnblogs.com/afanti/p/9219249.html
Copyright © 2011-2022 走看看