Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

how to pass these strings from php to javascript

i have 4 strings in my application like this that i want to pass to my js file

$a1='[10,20,13,14]';
$a2='[17,15,14,16]';
$a3='[18,24,16,17]';
$a4='[15,54,18,27]';

echo $a1.",".$a2.",".$a3.",".$a4;

and my javascriptcode is

$.ajax({
           type: "POST",
           dataType: "json",
           url: "loaddata.php",
               success: function(data)
            {
           alert(data); //alert 15,54,18,27


          }
     });

i can get just $a4 string, and i can not get other string

how can i pass these 4 strings in php and set these 4 variables in javascript

thanks;

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Encode them as JSON.

On the PHP side:

echo json_encode(array("a1" => $a1, "a2" => $a2, "a3" => $a3, "a4" => $a4));

On the JavaScript side:

$.ajax({
    type: "POST",
    dataType: "json",
    url: "loaddata.php",
    success: function(data) {
        var a1=data.a1;
        var a2=data.a2;
        var a3=data.a3;
        var a4=data.a4;
        // do something with a1, a2, a3 and a4
    }
});

And if you want a1, a2, a3, and a4 to be arrays of numbers instead of strings containing numbers, just JSON decode the strings on the PHP side before sending them over:

echo json_encode(array(
    "a1" => json_decode($a1),
    "a2" => json_decode($a2),
    "a3" => json_decode($a3),
    "a4" => json_decode($a4)
));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...