如何从PHP的JavaScript通过这些字符串 [英] how to pass these strings from php to javascript

查看:170
本文介绍了如何从PHP的JavaScript通过这些字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序像这样的四弦,我想传递给我的js文件

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;

和我的javascript code是

and my javascriptcode is

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


          }
     });

我能得到的只是$ A4字符串,我不能让其他的字符串

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

我如何能够通过这4个字符串在PHP和JavaScript中设置这些4个变量

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

感谢;

推荐答案

恩code它们作为JSON。

Encode them as JSON.

在PHP端:

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

在JavaScript端:

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
    }
});

如果你想要 A1 A2 A3 A4 是数字包含数字数组来代替字符串,C在PHP端的弦刚JSON德$ C $发送它们比之前:

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)
));

这篇关于如何从PHP的JavaScript通过这些字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆