如何在这里使用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未定义”
注意:我需要解决方案而不将x和y作为来自ajax的数据传递
答案 0 :(得分:1)
Javascript可以使用eval()
函数来解析从PHP
获得的字符串。对于一个简单的例子,我在下一个例子中删除了ajax调用以获取请求,但是你明白了。 This jsfiddle有一个有效的例子。
<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>
现在以上是你问题的实际答案,我仍然会反对。见why is using the javascript eval function a bad idea
如果没有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>
答案 1 :(得分:-1)
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"];
答案 2 :(得分:-1)
您是否尝试创建一个echo脚本,通过AJAX将变量发送到PHP脚本,然后PHP脚本返回该值?
如果是这样,您需要在AJAX请求的x
设置中提供data
,因为这样;
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;
<?php
$x = $_POST['x'];
$y = $_POST['y'];
exit("First string is $x, second string is $y");
我强烈建议您找一些关于JavaScript和PHP基础知识的教程,以了解其中的一些概念