简体   繁体   中英

Can ajax call on return add new javascript function to the page?

I have a jQuery ajax call that returns html of a table. Now I need to let user to do some javascript action on the table.

Can the return ajax response contain the javascript code or do I have to load the javascript code in the page on the first load of the page?

The user has the option of triggering the 'new' javascript. It doesn't have to triggered on ajax call.

To answer the actual question, the return response can contain the script. Simplest is to place it after the html, as the ready event has already fired in page it is being loaded into

You can use the success (or other event) callbacks provided with jQuery .ajax() to perform this JS action. Something like this:

$.ajax({
   success: function(){
     // Perform JS action
   }
}

The jQuery API lists all such event callbacks available for AJAX calls. Check this for more info.

The returned ajax response can contain javascript code as a string. Then you can eval(response).

If you want to request a script with ajax that will be run when retrieved, then you can use jQuery's getScript() method to retrieve it and then execute it.

Per the jQuery doc, getScript() is a shorthand for:

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

Which shows that jQuery's ajax command will handle a returned script for you automatically if you set the data type appropriately.

You can make your request a variable and extend upon it after the set up.

// Make the request to the server
var dataID = $("#WhatINeedForAParameter").val();
var request = $.ajax({
  url: "PageOrControllerOrWebApi/MethodName",
  type: "POST",
  data: { id : dataID },
  dataType: "json"
});

// When the request is done process
// what you need done
request.done(function(msg) {
  alert('You got this ' + msg);
});

// If the request failed you can
// see what the problem was and
// handle the situation accordingly
request.fail(function(jqXHR, textStatus) {
  alert( "Your request failed: " + textStatus );
});

you can do it using success callback i think this can be a way please try

$.ajax({
   .....,
   .....,
   success:  
    var script = document.createElement( 'script' );
    script.type = 'text/javascript';
    script.src = url;
    $("#tableID").append( script );
    });

i hope it should help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM