簡體   English   中英

AJAX從服務器請求另一個javascript或函數

[英]AJAX to request another javascript or function from the server

我們知道AJAX用於從服務器請求HTML格式的Web部件。 是否可以使用AJAX請求包含函數的腳本?

是的,您可以通過ajax加載JavaScript

http://api.jquery.com/jQuery.getScript/

$.getScript("ajax/test.js")
.done(function(script, textStatus) {
  console.log( textStatus );
})
.fail(function(jqxhr, settings, exception) {
  $( "div.log" ).text( "Triggered ajaxError handler." );
});

你也可以嘗試這樣的東西( 如何在通過ajax加載的html中運行javascript)中提到的:

require("extra.js", function () {
    functionDefinedInExtraJS();
});

//Sample require function:

function require(file, callback) {

    var script = document.getElementsByTagName('script')[0],
        newjs = document.createElement('script');

    // IE
    newjs.onreadystatechange = function () {
        if (newjs.readyState === 'loaded' || newjs.readyState === 'complete') {
            callback();
        }
    };

    // others
    newjs.onload = function () {
        callback();
    };

    newjs.src = file;
    script.parentNode.insertBefore(newjs, script);
}

另一種方法是使用eval()函數並將字符串回復轉換為工作的javascript代碼。

這是一個如何使用eval()來完成你需要的例子:

var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      eval(xmlhttp.responseText);
      // you can use whatever functionw as returned from the server from this line on :)
    }
  }

xmlhttp.open("GET","your-server-page-url",true);
xmlhttp.send();

是否可以使用AJAX請求包含函數的腳本?

對的,這是可能的。 這些功能可以在客戶端上執行。 例如,使用jQuery,您甚至可以使用一個允許您執行此類請求的函數: $.getScript

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM