gpt4 book ai didi

php - 为什么这会返回我 'undefined'

转载 作者:行者123 更新时间:2023-11-28 13:45:06 26 4
gpt4 key购买 nike

尝试运行一个脚本(test.al();),在 test.al 中,其名为 getcrypt.php();,php 脚本位于网络服务器上,并且正在运行。目前,这些是我的脚本

JS

var getcrypt = {
php: function () {

$.ajax({
url: "server.com/return.php",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
return v;
}
});
}
}

var test = {
al: function () {
a = getcrypt.php();
alert(a);
}
}

PHP

<?php
$id = $_POST['id'];
if ('getit' == $id){
$value = 'VALUE';
echo $value;
}else{
echo 0;
}
?>

这样,它会显示一个带有“unidefined”的警报,如果我添加一个alert(v);在 return v 之前,它会显示“VALUE”,但无法在变量之外使用它...

var getcrypt = {
php: function () {

$.ajax({
url: "server.com/return.php",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
alert(v);
return v;
}
});
}
}

这会给我一个带有正确值的警报(在“未定义”之后)

最佳答案

这是因为您正在进行异步调用。返回仅针对 success 函数,不针对 php 函数。

要获取该值,您需要编写:

var value;

var getcrypt = {
php: function (callback) {

$.ajax({
url: "",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
alert(v);
callback(v);
}
});
}
}

getcrypt.php(function(v) {
alert(v);
// This happens later than the below
value = v;
});

// The below will still not work since execution has already passed this place
// alert will still return undefined
alert(value);

关于php - 为什么这会返回我 'undefined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14893599/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com