How to execute the output of ajax script

I am getting ajax exit success data.

If the data contains some html text and script.

But the script is not executing, how can I execute the script.

Let's say the Ajax obj response is

<div>something....</div><script>alert("test");</script>

      

the above code is my Ajax response. The div gets rendered, but the warning doesn't work.

+2


source to share


5 answers


If you are fetching the JSON formatted result from the AJAX call, you can simply use eval to execute javascript.

Suppose if the json result is formed like this:



   var res =  '{"Data": "<something>",
              "script": "alert(something)"}';

   var out = eval("(" + res + ")");
   var data = out.data;
   eval(out.script);

      

+2


source


Assuming you are not using JSON or jQuery or any other library, and your AJAX call is returning some HTML and / or javascript which is appended to your existing document (e.g. using innerHTML), any javascript returned using AJAX is not will be executed in the browser - except for events on elements in HTML.

So, if your AJAX call returns <input type="button" value="Click me" onclick="alert('hello');" />

, the js warning will work fine, but if your AJAX call returns <script type="text/javascript">alert('hello');</script>

, it won't execute. In this case, you will have to parse the result in order to extract the javascript and execute it using a function like:



function extract_and_execute_js(output_to_parse)
{    
    if(output_to_parse != '')    
    {    
        var script = "";
        output_to_parse = output_to_parse.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(){if (output_to_parse !== null) script += arguments[1] + '\n';return '';});
        if(script) 
        {
            if (window.execScript)
            {
                window.execScript(script);
            }
            else
            {
                window.setTimeout(script, 0);
            }
        }
    }
}

      

+1


source


Interestingly, I'm using jQuery and using the html () function was enough to get the JavaScript done. So more or less I didn't have anything special.

There is a simplified version:

var myform = $('form#form-id');
$.post(myform.attr('action'), myform.serialize(), function(response) {
  $('#some-id').html(response.message);
}

      

In my case, the code kicked in automatically, so I don't need any of the other solutions suggested here.

+1


source


Not sure if you are using the library, but with Prototype I had to install

evalScripts: true

      

before JavaScript is evaluated. See here for more information:

http://www.sergiopereira.com/articles/prototype.js.html#UsingAjaxRequest

0


source


Using jQuery here is a simple bit of code:

$.ajax({
    type: "POST",
    url: "getData.asmx/HelloWorld",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(result) {
        alert(result);
    }
});

      

But for actually using the results of the variable result, I ended up using the javascript library, from http://www.json.org/js.html , I did:

success: function(result) {
    var myData = JSON.parse(result.d);

      

There are probably better approaches, but it was simple and worked for me, so I just use that. Later, when the project is in production, I can go back and clean it up, but this is after I have everything working.

0


source







All Articles