简体   繁体   中英

<script> tags not executing in ajax response

i am having the same problem as faced by many that the script tags are not executed in the jquery ajax response and i already tried the solutions with the 'eval()' method and similar but none is working.Is there any other way to accomplish this. i am sending a ajax request to a file cart.php from home.php

HOME.php

$.ajax({
    type:"POST",
    url:"cart.php?action=inc&id="+id+"&value="+myvalue+"&linecost="+linecost,
    cache:false,

    success: function(data)
    {
        alert(data);

i am actually converting a php array to a javascript array inside cart.php file like this:

CART.php:

 processing code here...

<?php    
$res=array($val,$cost,$total);
    foreach ($res as $a) {
    $string .= "\"" . $a . "\", ";
    $final = substr($string, 0 ,(strlen($string) - 2));
    }
?>
<script>var j = new Array(<?php echo $final; ?>);</script>

Returned data at home.php inside data variable:

<script>var j = new Array("4", "2928", "6708");</script>

Now i just want the elements of this array but it is returning the whole line at the calling file inside the 'success' function..how do i extract the values at the calling file?Any help?

You want to use JSON. Instead of returning the script, you can use json_encode .

 echo json_encode($final);

Then to convert the JSON back to an array you can do in JS:

 var result=JSON.parse(data);

result is now a normal JS array containing the same data as in $final .

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