在jQuery函数中将结果从AJAX返回到PHP变量


Return result to a PHP variable from AJAX in a jQuery function

所以这是我尝试过的最难的事情,搜索一天后我找不到任何答案。请注意,我正在使用一些自定义jQuery API,并将解释它的作用。

设置是一个php页面,其中包含一个jQuery函数。jQuery函数调用API返回基于我单击的行的结果(它是jQgrid,基本上看起来像一个在线的excel表)。这很好,但目标是从jQuery函数中获得结果OUT,并将其存储在PHP变量中。我只是一无所知。。。。。。

PHP主页:

$getUnitID = <<<getUnitID //This is the jQuery function. It is stored in a php variable for use in other functions of the API
function(rowid, selected)
{
    var selr= null;
    if(rowid != null){ 
        selr = jQuery('#grid').jqGrid('getGridParam','selrow'); //This will give ma a number result based on the row I selected. Works fine.
        $.ajax({ // I believe I need to use AJAX so here is my attempt
            type: "POST",
            url: "getId.php", //This is another PHP page for the reuslt. See below
            dataType: "json",
            data: {selr:selr},      
            success: function(data) { 
                alert (data); // This will successfully show me the row number I chose as an alert. But I don't want an alert, I want it stored as a php variable in my main document to use elsewhere.
            }
        });
    }
}
getUnitID; //End of the function
$grid->setGridEvent('onSelectRow',$getUnitID); //Just an event that calls the function upon clicking the row
$rowResult = ??????? //I need this variable to store the result of that AJAX call or that function call

getId.php

<?php
$rId = $_POST["selr"];
echo $rId;
?>

从本质上讲,我不知道为什么要使用AJAX,因为我的结果仍然停留在主jQuery函数中。看在上帝的份上,我怎么能把它放在函数之外?!?!?!?!?!?!?!我需要$_GETPOST发给getId.php的"selr"吗?如果是,如何?

谢谢你们,我爱你们所有人。

当您发出AJAX请求并收到响应时,PHP已经进入睡眠状态。您不能将数据返回到同一页面的PHP代码。PHP在服务器上完成工作很久之后,jQuery就开始在client计算机上执行。

JavaScript函数是否存储在PHP变量中并不重要。PHP将无法返回其输出。唯一能做到这一点的方法是对该代码发起另一个新请求并向其发送值。但在同一页面上的同一请求上,它是一个no

如何将数据发送到另一个PHP页面的示例

//Your existing jQuery
success: function(data) { 
 // alert (data); 
 var result=data;
 $.ajax({
 type: "POST",
 url: "anotherpage.php",
 data: { data: result }
});
}