jQuery ajax - getScript() method

Tarihin wutar

A cikin ra'ayin AJAX, ta kai wuce kuma ya tattara wuce JavaScript:

$("button").click(function(){
  $.getScript("demo_ajax_script.js");
});

Kai amfani da shi a yau

Tatawurin kuma amfani

getScript() method ne ta hanyar HTTP GET ta kai wuce kuma ya tattara JavaScript wuce.

Gonin

jQuery.getScript(url,success(response,status))
Parameters Bayanai
url URL na zai zama a kori.
success(response,status)

Optional. Tashin hanyar hukuntar kariya a cikin ra'ayin nasara.

Parameters:

  • response - Tsarin koyaushe na ra'ayi daga ra'ayin
  • status - Tsarin koyaushe na ra'ayi ("success", "notmodified", "error", "timeout" ko "parsererror")

Bayanai

Hukuntar kariya ce ta yanki, kuma ta yi tasiri da Ajax, kuma ta yi tasiri da:

$.ajax({
  url: url,
  dataType: "script",
  success: success
});

Hukuntar kariya ce ta hanyar JavaScript wanda zai zama. Akwai kuma kuma ba a fi amin da shi ba saboda ayya'ana koyaushe script ne ya baya.

Loaded scripts execute in the global environment, so they can reference other variables and use jQuery functions.

For example, loading a test.js file that contains the following code:

$(".result").html("<p>Lorem ipsum dolor sit amet.</p>");

By referencing this filename, you can load and run this script:

$.getScript("ajax/test.js", function() {
  alert("Load was performed.");
});

Note:Before jQuery 1.2 version, getScript could only call JS files from the same domain. In 1.2, you can call JavaScript files across domains. Note: Safari 2 or earlier versions cannot execute scripts in the global scope synchronously. If scripts are added using getScript, please add a delay function.

More examples

Example 1

Load and execute test.js:

$.getScript("test.js");

Example 2

Load and execute test.js, and then display the message:

$.getScript("test.js", function(){
  alert("Script loaded and executed.");
});

Example 3

load jQuery official color animation plugin After successful binding of color change animation:

HTML code:

<button id="go">Run</button>
<div class="block"></div>

jQuery code:

jQuery.getScript("http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js",
 function(){
  $("#go").click(function(){
    $(".block").animate( { backgroundColor: 'pink' }, 1000)
      .animate( { backgroundColor: 'blue' }, 1000);
  });
});