在Ajax响应中返回Javascript变量


Return Javascript Variable in Ajax Response

如何在这里使用eval()函数
ajax.js

 var x="hello world";
 var y="anyother string";
    $.ajax({
        url:"ajax.php",
        success:function(data){
            console.log($.globalEval(data));
        }
    });

ajax.php

<?php exit("'first string is '+x+' second one is'+y");?>

我想返回x,y作为ajax响应的变量,所以console.log(data)可以打印

的值
first string is hello world second one is another string  

但是显示"x is undefine"

注意:我需要的解决方案不传递x和y作为数据从ajax

Javascript可以使用eval()函数来解析从PHP得到的字符串。对于一个简单的示例,在下一个示例中我省略了ajax调用来获取请求,但是您可以理解。本文提供了一个工作示例。

<script>
var x="hello world";
var y="anyother string";
//normally you would get this from ajax
var str = "'first string is '+x+' second one is'+y";
//complete will contain the full string after eval.
var complete = '';
eval('complete=' + str);

alert(complete); //first string is hello world second one isanyother string
</script>

在您的例子中,当您使用AJAX时,它将变成

<script>
var x="hello world";
var y="anyother string";
$.ajax({
  url:"ajax.php",
  success:function(data){
    //complete will contain the full string after eval.
    var complete = '';
    eval('complete=' + data);
    console.log(complete);
  }
});
</script>

现在以上是你问题的实际答案,我仍然反对它。看看为什么使用javascript eval函数是个坏主意

如果不使用eval,可以使用

<script>
var x = "hello world";
var y = "anyother string";
//normally you would get this from ajax
var str = "first string is {x} second one is {y}";
//complete will contain the full string after eval.
var complete = str.replace('{x}', x).replace('{y}', y);
alert(complete); //first string is hello world second one isanyother string
</script>

ajax.js:

  $.ajax({
        method: "post",
        url:"ajax.php",
        data: {x: "helloworld", y:"another string"},
        success:function(data){
            console.log(data);
        }
    });

ajax.php:

echo "First string: ".$_POST['x'].", second string: ".$_POST["y"];

您是否尝试创建一个echo脚本,通过AJAX向PHP脚本发送一个变量,然后PHP脚本返回该值?

如果是这样,您需要在data设置中为AJAX请求提供x,如下所示;

var x="helloworld";
$.ajax({
    url:"ajax.php",
    data: {
        x: x
    }
    success:function(data){
        console.log(data);
    }
});

然后在PHP脚本中,需要从POST数组中检索值,并将其作为响应输出:

<?php
exit($_POST['x']);

编辑

包含第二个变量(y)

var x="helloworld",
    y="another string";
$.ajax({
    url:"ajax.php",
    data: {
        x: x,
        y: y
    }
    success:function(data){
        console.log(data);
    }
});
<?php
$x = $_POST['x'];
$y = $_POST['y'];
exit("First string is $x, second string is $y");

我强烈建议找一些关于JavaScript和PHP基础的教程来理解这些概念