简体   繁体   中英

script doesn't load after ajax response

I was trying to make an ajax call and show an html part inside a div class. For that i used the following way.

$.ajax({
    type: "get",
    url: "{{url('searchByCheckbox')}}",
    dataType: 'html',
      success: function(html)
        {
           $(".infinite-scroll").html(html)
        }   
});

But the problem is there is a script inside that html part which i wanted to load when i make first ajax call it's not loaded but for the second one it's loaded the script. suppose the html response like this :

<script>
  alert()
</script>
// html

How do i make it work? I put the script above the html page which i'm getting as response.

(those who are marking the Question as duplicate should read at least what i want and what they wanted )

Im sure that the error is happening because of the script, because you are closing the </script> tag inside the html.

The best solution is to return the data from your ajax call as a json

To do that you should:

1- add a dataType to your ajax parameter as the below:

$.ajax({
    type: "get",
    dataType: "json",

2- In the php file handling the ajax call, you must resurn the values as a json as below:

Assume that currently you are doing the following:

echo $html

You should change it to match the below:

$retArr = array(
    "html"     => $html, //Your html code without the javascript function
    "jsFunc"   => $jsFunc //Your java script function parameters
) ;
echo json_encode($retArr) ;

And then your ajax success must be as the below:

success: function(data)
    { //You can access all the object parametes by calling the object name `data` followed by a dot `.` and then by the parameter key
       data.jsFunc // Your javascript function params
       $(".infinite-scroll").html(data.html) ;
    } 

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