溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Django 通過JS實現(xiàn)ajax過程詳解

發(fā)布時間:2020-10-13 06:10:03 來源:腳本之家 閱讀:140 作者:搶魚 欄目:開發(fā)技術(shù)

ajax的優(yōu)缺點

AJAX使用Javascript技術(shù)向服務(wù)器發(fā)送異步請求

AJAX無須刷新整個頁面

因為服務(wù)器響應(yīng)內(nèi)容不再是整個頁面,而是頁面中的局部,所以AJAX性能高

小練習(xí):計算兩個數(shù)的和

方式一:這里沒有指定contentType:默認是urlencode的方式發(fā)的

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width">
  <title>Title</title>
  <script src="/static/jquery-3.2.1.min.js"></script>
  <script src="http://apps.bdimg.com/libs/jquery.cookie/1.4.1/jquery.cookie.js"></script>
</head>
<body>
<h2>計算兩個數(shù)的和,測試ajax</h2>
<input type="text" class="num1">+<input type="text" class="num2">=<input type="text" class="ret">
<button class="send_ajax">sendajax</button>

<script>
  $(".send_ajax").click(function () {
     $.ajax({
      url:"/sendAjax/",
      type:"post",
      headers:{"X-CSRFToken":$.cookie('csrftoken')},  
      data:{
        num1:$(".num1").val(),
        num2:$(".num2").val(),
      },
      success:function (data) {
        alert(data);
        $(".ret").val(data)
      }
    })
  })

</script>
</body>
</html>

views.py

def index(request):
  return render(request,"index.html")

def sendAjax(request):
  print(request.POST)
  print(request.GET)
  print(request.body) 
  num1 = request.POST.get("num1")
  num2 = request.POST.get("num2")
  ret = float(num1)+float(num2)
  return HttpResponse(ret)

方式二:指定conentType為json數(shù)據(jù)發(fā)送:

<script>
  $(".send_ajax").click(function () {
     $.ajax({
      url:"/sendAjax/",
      type:"post",
      headers:{"X-CSRFToken":$.cookie('csrftoken')},  //如果是json發(fā)送的時候要用headers方式解決forbidden的問題
      data:JSON.stringify({
        num1:$(".num1").val(),
        num2:$(".num2").val()
      }),
      contentType:"application/json", //客戶端告訴瀏覽器是以json的格式發(fā)的數(shù)據(jù),所以的吧發(fā)送的數(shù)據(jù)轉(zhuǎn)成json字符串的形式發(fā)送
      success:function (data) {
        alert(data);
        $(".ret").val(data)
      }
    })
  })

</script>

views.py

def sendAjax(request):
  import json
  print(request.POST) #<QueryDict: {}>
  print(request.GET)  #<QueryDict: {}>
  print(request.body) #b'{"num1":"2","num2":"2"}' 注意這時的數(shù)據(jù)不再POST和GET里,而在body中
  print(type(request.body.decode("utf8"))) # <class 'str'>
  # 所以取值的時候得去body中取值,首先得反序列化一下
  data = request.body.decode("utf8")
  data = json.loads(data)
  num1= data.get("num1")
  num2 =data.get("num2")
  ret = float(num1)+float(num2)
  return HttpResponse(ret)

JS實現(xiàn)的ajax

其實AJAX就是在Javascript中多添加了一個對象:XMLHttpRequest對象。所有的異步交互都是使用XMLHttpServlet對象完成的。也就是說,我們只需要學(xué)習(xí)一個Javascript的新對象即可。

var xmlHttp = new XMLHttpRequest();//(大多數(shù)瀏覽器都支持DOM2規(guī)范)

注意,各個瀏覽器對XMLHttpRequest的支持也是不同的!為了處理瀏覽器兼容問題,給出下面方法來創(chuàng)建XMLHttpRequest對象:

function createXMLHttpRequest() {
    var xmlHttp;
    // 適用于大多數(shù)瀏覽器,以及IE7和IE更高版本
    try{
      xmlHttp = new XMLHttpRequest();
    } catch (e) {
      // 適用于IE6
      try {
        xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
        // 適用于IE5.5,以及IE更早版本
        try{
          xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e){}
      }
    }      
    return xmlHttp;
  }

二、使用流程

1、打開與服務(wù)器的連接(open)

當?shù)玫絏MLHttpRequest對象后,就可以調(diào)用該對象的open()方法打開與服務(wù)器的連接了。open()方法的參數(shù)如下:

open(method, url, async):

method:請求方式,通常為GET或POST;

url:請求的服務(wù)器地址,例如:/ajaxdemo1/AServlet,若為GET請求,還可以在URL后追加參數(shù);

async:這個參數(shù)可以不給,默認值為true,表示異步請求;

2、發(fā)送請求

當使用open打開連接后,就可以調(diào)用XMLHttpRequest對象的send()方法發(fā)送請求了。send()方法的參數(shù)為POST請求參數(shù),即對應(yīng)HTTP協(xié)議的請求體內(nèi)容,若是GET請求,需要在URL后連接參數(shù)。

注意:若沒有參數(shù),需要給出null為參數(shù)!若不給出null為參數(shù),可能會導(dǎo)致FireFox瀏覽器不能正常發(fā)送請求!

xmlHttp.send(null);

3、接收服務(wù)器的響應(yīng)(5個狀態(tài),4個過程)

當請求發(fā)送出去后,服務(wù)器端就開始執(zhí)行了,但服務(wù)器端的響應(yīng)還沒有接收到。接下來我們來接收服務(wù)器的響應(yīng)。

XMLHttpRequest對象有一個onreadystatechange事件,它會在XMLHttpRequest對象的狀態(tài)發(fā)生變化時被調(diào)用。下面介紹一下XMLHttpRequest對象的5種狀態(tài):

0:初始化未完成狀態(tài),只是創(chuàng)建了XMLHttpRequest對象,還未調(diào)用open()方法;

1:請求已開始,open()方法已調(diào)用,但還沒調(diào)用send()方法;

2:請求發(fā)送完成狀態(tài),send()方法已調(diào)用;

3:開始讀取服務(wù)器響應(yīng);

4:讀取服務(wù)器響應(yīng)結(jié)束。

onreadystatechange事件會在狀態(tài)為1、2、3、4時引發(fā)。

下面代碼會被執(zhí)行四次!對應(yīng)XMLHttpRequest的四種狀態(tài)!

xmlHttp.onreadystatechange = function() {
      alert('hello');
    };

但通常我們只關(guān)心最后一種狀態(tài),即讀取服務(wù)器響應(yīng)結(jié)束時,客戶端才會做出改變。我們可以通過XMLHttpRequest對象的readyState屬性來得到XMLHttpRequest對象的狀態(tài)。

xmlHttp.onreadystatechange = function() {
      if(xmlHttp.readyState == 4) {
        alert('hello');  
      }
    };

其實我們還要關(guān)心服務(wù)器響應(yīng)的狀態(tài)碼xmlHttp.status是否為200,其服務(wù)器響應(yīng)為404,或500,那么就表示請求失敗了。我們可以通過XMLHttpRequest對象的status屬性得到服務(wù)器的狀態(tài)碼。

最后,我們還需要獲取到服務(wù)器響應(yīng)的內(nèi)容,可以通過XMLHttpRequest對象的responseText得到服務(wù)器響應(yīng)內(nèi)容。

xmlHttp.onreadystatechange = function() {
      if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        alert(xmlHttp.responseText);  
      }
    };

需要注意的:

如果是post請求:

基于JS的ajax沒有Content-Type這個參數(shù)了,也就不會默認是urlencode這種形式了,需要我們自己去設(shè)置

<1>需要設(shè)置請求頭:xmlHttp.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”);

注意 :form表單會默認這個鍵值對不設(shè)定,Web服務(wù)器會忽略請求體的內(nèi)容。

<2>在發(fā)送時可以指定請求體了:xmlHttp.send(“username=yuan&password=123”)

基于jQuery的ajax和form發(fā)送的請求,都會默認有Content-Type,默認urlencode,
Content-Type:客戶端告訴服務(wù)端我這次發(fā)送的數(shù)據(jù)是什么形式的

dataType:客戶端期望服務(wù)端給我返回我設(shè)定的格式

如果是get請求:

xmlhttp.open("get","/sendAjax/?a=1&b=2");

小練習(xí):和上面的練習(xí)一樣,只是換了一種方式(可以和jQuery的對比一下)

<script>
方式一=======================================
  //基于JS實現(xiàn)實現(xiàn)用urlencode的方式
  var ele_btn = document.getElementsByClassName("send_ajax")[0];
  ele_btn.onclick = function () { //綁定事件
    alert(5555);
    //發(fā)送ajax:有一下幾步
    //(1)獲取XMLResquest對象
    xmlhttp = new XMLHttpRequest();
    //(2)連接服務(wù)器
    //get請求的時候,必用send發(fā)數(shù)據(jù),直接在請求路徑里面發(fā)
{#    xmlhttp.open("get","/sendAjax/?a=1&b=2");//open里面的參數(shù),請求方式,請求路徑#}
    //post請求的時候,需要用send發(fā)送數(shù)據(jù)
    xmlhttp.open("post","/sendAjax/");
    //設(shè)置請求頭的Content-Type
    xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    //(3)發(fā)送數(shù)據(jù)
    var ele_num1 = document.getElementsByClassName("num1")[0];
    var ele_num2 = document.getElementsByClassName("num2")[0];
    var ele_ret = document.getElementsByClassName("ret")[0];
    var ele_scrf = document.getElementsByName("csrfmiddlewaretoken")[0];


    var s1 = "num1="+ele_num1.value;
    var s2 = "num2="+ele_num2.value;
    var s3 = "&csrfmiddlewaretoken="+ele_scrf.value;
    xmlhttp.send(s1+"&"+s2+s3); //請求數(shù)據(jù)
    //(4)回調(diào)函數(shù),success
    xmlhttp.onreadystatechange = function () {
      if (this.readyState==4&&this.status==200){
        alert(this.responseText);
        ele_ret.value = this.responseText
      }
    }
  }
方式二====================================================
{#  ===================json=============#}
  var ele_btn=document.getElementsByClassName("send_ajax")[0];
  ele_btn.onclick=function () {

    // 發(fā)送ajax

     // (1) 獲取 XMLHttpRequest對象
     xmlHttp = new XMLHttpRequest();

     // (2) 連接服務(wù)器
    // get
    //xmlHttp.open("get","/sendAjax/?a=1&b=2");

    // post
    xmlHttp.open("post","/sendAjax/");

    // 設(shè)置請求頭的Content-Type
    var ele_csrf=document.getElementsByName("csrfmiddlewaretoken")[0];
    xmlHttp.setRequestHeader("Content-Type","application/json");
    xmlHttp.setRequestHeader("X-CSRFToken",ele_csrf.value); //利用js的方式避免forbidden的解決辦法

    // (3) 發(fā)送數(shù)據(jù)
     var ele_num1 = document.getElementsByClassName("num1")[0];
    var ele_num2 = document.getElementsByClassName("num2")[0];
    var ele_ret = document.getElementsByClassName("ret")[0];


    var s1 = ele_num1.value;
    var s2 = ele_num2.value;
    xmlHttp.send(JSON.stringify(
      {"num1":s1,"num2":s2}
    )) ;  // 請求體數(shù)據(jù)
    // (4) 回調(diào)函數(shù) success
    xmlHttp.onreadystatechange = function() {
      if(this.readyState==4 && this.status==200){
        console.log(this.responseText);
        ele_ret.value = this.responseText
      }
    };
  }

</script>

views.py

def sendAjax(request):
  num1=request.POST.get("num1")
  num2 = request.POST.get("num2")
  ret = float(num1)+float(num2)
  return HttpResponse(ret)

JS實現(xiàn)ajax小結(jié)

創(chuàng)建XMLHttpRequest對象;

調(diào)用open()方法打開與服務(wù)器的連接;

調(diào)用send()方法發(fā)送請求;

為XMLHttpRequest對象指定onreadystatechange事件函數(shù),這個函數(shù)會在

XMLHttpRequest的1、2、3、4,四種狀態(tài)時被調(diào)用;

XMLHttpRequest對象的5種狀態(tài),通常我們只關(guān)心4狀態(tài)。

XMLHttpRequest對象的status屬性表示服務(wù)器狀態(tài)碼,它只有在readyState為4時才能獲取到。

XMLHttpRequest對象的responseText屬性表示服務(wù)器響應(yīng)內(nèi)容,它只有在

readyState為4時才能獲取到!

總結(jié):

- 如果"Content-Type"="application/json",發(fā)送的數(shù)據(jù)是對象形式的{},需要在body里面取數(shù)據(jù),然后反序列化

= 如果"Content-Type"="application/x-www-form-urlencoded",發(fā)送的是/index/?name=haiyan&agee=20這樣的數(shù)據(jù),

如果是POST請求需要在POST里取數(shù)據(jù),如果是GET,在GET里面取數(shù)據(jù)

<h2>AJAX</h2>
<button onclick="send()">測試</button>
<div id="div1"></div>


<script>
    function createXMLHttpRequest() {
      try {
        return new XMLHttpRequest();//大多數(shù)瀏覽器
      } catch (e) {
        try {
          return new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
          return new ActiveXObject("Microsoft.XMLHTTP");
        }
      }
    }

    function send() {
      var xmlHttp = createXMLHttpRequest();
      xmlHttp.onreadystatechange = function() {
        if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
          var div = document.getElementById("div1");
          div.innerText = xmlHttp.responseText;
          div.textContent = xmlHttp.responseText;
        }
      };

      xmlHttp.open("POST", "/ajax_post/", true);
      //post: xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      xmlHttp.send(null); //post: xmlHttp.send("b=B");
    }


</script>
    
#--------------------------------views.py 
from django.views.decorators.csrf import csrf_exempt

def login(request):
  print('hello ajax')
  return render(request,'index.html')

@csrf_exempt  #csrf防御
def ajax_post(request):
  print('ok')
  return HttpResponse('helloyuanhao')

實例(用戶名是否已被注冊)

功能介紹

在注冊表單中,當用戶填寫了用戶名后,把光標移開后,會自動向服務(wù)器發(fā)送異步請求。服務(wù)器返回true或false,返回true表示這個用戶名已經(jīng)被注冊過,返回false表示沒有注冊過。

客戶端得到服務(wù)器返回的結(jié)果后,確定是否在用戶名文本框后顯示“用戶名已被注冊”的錯誤信息!

案例分析

頁面中給出注冊表單;

在username表單字段中添加onblur事件,調(diào)用send()方法;

send()方法獲取username表單字段的內(nèi)容,向服務(wù)器發(fā)送異步請求,參數(shù)為username;

django 的視圖函數(shù):獲取username參數(shù),判斷是否為“yuan”,如果是響應(yīng)true,否則響應(yīng)false

script type="text/javascript">
    function createXMLHttpRequest() {
      try {
        return new XMLHttpRequest();
      } catch (e) {
        try {
          return new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
          return new ActiveXObject("Microsoft.XMLHTTP");
        }
      }
    }

    function send() {
      var xmlHttp = createXMLHttpRequest();
      xmlHttp.onreadystatechange = function() {
        if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
          if(xmlHttp.responseText == "true") {
            document.getElementById("error").innerText = "用戶名已被注冊!";
            document.getElementById("error").textContent = "用戶名已被注冊!";
          } else {
            document.getElementById("error").innerText = "";
            document.getElementById("error").textContent = "";
          }
        }
      };
      xmlHttp.open("POST", "/ajax_check/", true, "json");
      xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      var username = document.getElementById("username").value;
      xmlHttp.send("username=" + username);
    }
</script>

//--------------------------------------------------index.html

<h2>注冊</h2>
<form action="" method="post">
用戶名:<input id="username" type="text" name="username" onblur="send()"/><span id="error"></span><br/>
密 碼:<input type="text" name="password"/><br/>
<input type="submit" value="注冊"/>
</form>


//--------------------------------------------------views.py
from django.views.decorators.csrf import csrf_exempt

def login(request):
  print('hello ajax')
  return render(request,'index.html')
  # return HttpResponse('helloyuanhao')

@csrf_exempt
def ajax_check(request):
  print('ok')

  username=request.POST.get('username',None)
  if username=='yuan':
    return HttpResponse('true')
  return HttpResponse('false')

同源策略與Jsonp

同源策略(Same origin policy)是一種約定,它是瀏覽器最核心也最基本的安全功能,如果缺少了同源策略,則瀏覽器的正常功能可能都會受到影響??梢哉fWeb是構(gòu)建在同源策略基礎(chǔ)之上的,瀏覽器只是針對同源策略的一種實現(xiàn)。

同源策略,它是由Netscape提出的一個著名的安全策略?,F(xiàn)在所有支持JavaScript 的瀏覽器都會使用這個策略。所謂同源是指,域名,協(xié)議,端口相同。當一個瀏覽器的兩個tab頁中分別打開來 百度和谷歌的頁面當瀏覽器的百度tab頁執(zhí)行一個腳本的時候會檢查這個腳本是屬于哪個頁面的,即檢查是否同源,只有和百度同源的腳本才會被執(zhí)行。如果非同源,那么在請求數(shù)據(jù)時,瀏覽器會在控制臺中報一個異常,提示拒絕訪問。

jsonp(jsonpadding)

之前發(fā)ajax的時候都是在自己給自己的當前的項目下發(fā)

現(xiàn)在我們來實現(xiàn)跨域發(fā)。給別人的項目發(fā)數(shù)據(jù),

示例,先來測試一下

項目1:

==================================================8001項目的index
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>

<button>ajax</button>
{% csrf_token %}

<script>
  $("button").click(function(){
    $.ajax({
      url:"http://127.0.0.1:7766/SendAjax/",
      type:"POST",
      data:{"username":"yuan","csrfmiddlewaretoken":$("[name='csrfmiddlewaretoken']").val()},
      success:function(data){
        alert(123);
        alert(data)
      }
    })
  })
</script>
</body>
</html>
==================================:8001項目的views
def index(request):

  return render(request,"index.html")

def ajax(request):
  import json
  print(request.POST,"+++++++++++")
  return HttpResponse(json.dumps("hello"))

項目2:

==================================:8002項目的index
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<button>sendAjax</button>
{% csrf_token %}
<script>
  $("button").click(function(){
    $.ajax({
      url:"/SendAjax/",
      type:"POST",
      data:{"username":"yuan","csrfmiddlewaretoken":$("[name='csrfmiddlewaretoken']").val()},
      success:function(data){
        alert(data)
      }
    })
  })
</script>
</body>
</html>
==================================:8002項目的views
def index(request):
  return render(request,"index.html")
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def SendAjax(request):
  import json
  print("++++++++")
  return HttpResponse(json.dumps("hello2"))

當點擊項目1的按鈕時,發(fā)送了請求,但是會發(fā)現(xiàn)報錯如下:

已攔截跨源請求:同源策略禁止讀取位于 http://127.0.0.1:7766/SendAjax/ 的遠程資源。(原因:CORS 頭缺少 'Access-Control-Allow-Origin')。

但是注意,項目2中的訪問已經(jīng)發(fā)生了,說明是瀏覽器對非同源請求返回的結(jié)果做了攔截。

注意:a標簽,form,img標簽,引用cdn的css等也屬于跨域(跨不同的域拿過來文件來使用),不是所有的請求都給做跨域,(為什么要進行跨域呢?因為我想用人家的數(shù)據(jù),所以得去別人的url中去拿,借助script標簽)

<script src="http://127.0.0.1:8002/ajax_send2/">
  項目二
</script>

只有發(fā)ajax的時候給攔截了,所以要解決的問題只是針對ajax請求能夠?qū)崿F(xiàn)跨域請求

解決同源策源的兩個方法:

<script src="http://code.jquery.com/jquery-latest.js"></script>

借助script標簽,實現(xiàn)跨域請求,示例:

8001/index

<button>ajax</button>
{% csrf_token %}
<script>
  function func(name){
    alert(name)
  }
</script>
<script src="http://127.0.0.1:7766/SendAjax/"></script>
# =============================:8002/
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def SendAjax(request):
  import json
  print("++++++++")
  # dic={"k1":"v1"}
return HttpResponse("func('yuan')") # return HttpResponse("func('%s')"%json.dumps(dic))

這其實就是JSONP的簡單實現(xiàn)模式,或者說是JSONP的原型:創(chuàng)建一個回調(diào)函數(shù),然后在遠程服務(wù)上調(diào)用這個函數(shù)并且將JSON 數(shù)據(jù)形式作為參數(shù)傳遞,完成回調(diào)。

將JSON數(shù)據(jù)填充進回調(diào)函數(shù),這就是JSONP的JSON+Padding的含義。

但是以上的方式也有不足,回調(diào)函數(shù)的名字和返回的那個名字的一致。并且一般情況下,我們希望這個script標簽?zāi)軌騽討B(tài)的調(diào)用,而不是像上面因為固定在html里面所以沒等頁面顯示就執(zhí)行了,很不靈活。我們可以通過javascript動態(tài)的創(chuàng)建script標簽,這樣我們就可以靈活調(diào)用遠程服務(wù)了。

解決辦法:javascript動態(tài)的創(chuàng)建script標簽

<button onclick="f()">sendAjax</button>
<script>
  function addScriptTag(src){
     var script = document.createElement('script');
     script.setAttribute("type","text/javascript");
     script.src = src;
     document.body.appendChild(script);
     document.body.removeChild(script);
  }
  function func(name){
    alert("hello"+name)
  }
  function f(){
     addScriptTag("http://127.0.0.1:7766/SendAjax/")
  }
</script>

為了更加靈活,現(xiàn)在將你自己在客戶端定義的回調(diào)函數(shù)的函數(shù)名傳送給服務(wù)端,服務(wù)端則會返回以你定義的回調(diào)函數(shù)名的方法,將獲取的json數(shù)據(jù)傳入這個方法完成回調(diào):

將8001的f()改寫為:

function f(){
     addScriptTag("http://127.0.0.1:7766/SendAjax/?callbacks=func")
  }

8002的views改為:

def SendAjax(request): 
  import json 
  dic={"k1":"v1"} 
  print("callbacks:",request.GET.get("callbacks"))
  callbacks=request.GET.get("callbacks") #注意要在服務(wù)端得到回調(diào)函數(shù)名的名字 
  return HttpResponse("%s('%s')"%(callbacks,json.dumps(dic)))

jQuery對JSONP的實現(xiàn)

getJSON

jQuery框架也當然支持JSONP,可以使用$.getJSON(url,[data],[callback])方法

8001的html改為:

<button onclick="f()">sendAjax</button>
<script>
  function f(){
     $.getJSON("http://127.0.0.1:7766/SendAjax/?callbacks=?",function(arg){
      alert("hello"+arg)
    });
  }  
</script>

8002的views不改動。

結(jié)果是一樣的,要注意的是在url的后面必須添加一個callback參數(shù),這樣getJSON方法才會知道是用JSONP方式去訪問服務(wù),callback后面的那個問號是內(nèi)部自動生成的一個回調(diào)函數(shù)名。

此外,如果說我們想指定自己的回調(diào)函數(shù)名,或者說服務(wù)上規(guī)定了固定回調(diào)函數(shù)名該怎么辦呢?我們可以使用$.ajax方法來實現(xiàn)

8001的html改為:

<script>

  function f(){
     $.ajax({
        url:"http://127.0.0.1:7766/SendAjax/",
        dataType:"jsonp",
        jsonp: 'callbacks',
        jsonpCallback:"SayHi"
      });

    }
  function SayHi(arg){
        alert(arg);
      }
</script>

8002的views不改動。

當然,最簡單的形式還是通過回調(diào)函數(shù)來處理:

<script>
  function f(){
      $.ajax({
        url:"http://127.0.0.1:7766/SendAjax/",
        dataType:"jsonp",      //必須有,告訴server,這次訪問要的是一個jsonp的結(jié)果。
        jsonp: 'callbacks',     //jQuery幫助隨機生成的:callbacks="wner"
        success:function(data){
          alert("hi "+data)
       }
     });
    }
</script>

jsonp: 'callbacks'就是定義一個存放回調(diào)函數(shù)的鍵,jsonpCallback是前端定義好的回調(diào)函數(shù)方法名'SayHi',server端接受callback鍵對應(yīng)值后就可以在其中填充數(shù)據(jù)打包返回了;

jsonpCallback參數(shù)可以不定義,jquery會自動定義一個隨機名發(fā)過去,那前端就得用回調(diào)函數(shù)來處理對應(yīng)數(shù)據(jù)了。利用jQuery可以很方便的實現(xiàn)JSONP來進行跨域訪問?!?/p>

注意 JSONP一定是GET請求

應(yīng)用

<input type="button" onclick="AjaxRequest()" value="跨域Ajax" />

<div id="container"></div>

  <script type="text/javascript">
    function AjaxRequest() {
      $.ajax({
        url: 'http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403',
        type: 'GET',
        dataType: 'jsonp',
        jsonp: 'callback',
        jsonpCallback: 'list',
        success: function (data) {
          
          $.each(data.data,function(i){
            var item = data.data[i];
            var str = "<p>"+ item.week +"</p>";
            $('#container').append(str);
            $.each(item.list,function(j){
              var temp = "<a href='" + item.list[j].link +"'>" + item.list[j].name +" </a><br/>";
              $('#container').append(temp);
            });
            $('#container').append("<hr/>");
          })

        }
      });
    }
</script>

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI