【问题标题】:Passing values from jQuery to PHP in same page instantly立即在同一页面中将值从 jQuery 传递到 PHP
【发布时间】:2014-11-05 19:13:31
【问题描述】:

我编写了一个 PHP 程序,通过 jQuery 确认消息(参考:http://rathur.fr/jQuery/MsgBox/)确认删除数据,并立即将结果记录回同一页面。如果页面刷新,它将返回到之前的状态。

行的部分如下:

print "
<script type='text/javascript'>
$(document).ready(function(){
  $.msgbox('<br/>Are you sure you want to delete the selected record from the database?', {
    type : 'confirm'
  }, function(result){
    $('#output').text(result);
    var output = result;
  });
});
</script>";

我想立即将操作按钮的结果传递给 PHP 变量,如下所示(只是一个试验):

$x = $_SESSION['output']; OR
$x = $_POST['output']; OR
$x = print "<div id=\"output\"></div>"; OR
$x = some_function(output);

请帮助我,或者建议是否有其他更好的选择。

【问题讨论】:

  • 您需要通过 AJAX 调用将数据 POST 回 php,以便在第二遍使用服务器端代码。
  • 你能指定改变现有jQuery脚本的方法吗?

标签: javascript php jquery msgbox


【解决方案1】:

这里是一个简单的 Ajax 事件对 PHP 文件的调用:单击一个按钮。

Javascript 客户端:

 $("body").on("click", "#mybutton", function() {
            var mydata = $("#form").serialize();
            $.ajax({
                type: "POST",
                url: "/api/api.php",
                data: {data : mydata},
                timeout: 6e3,
                error: function(a, b) {
                    if ("timeout" == b) $("#err-timedout").slideDown("slow"); else {
                        $("#err-state").slideDown("slow");
                        $("#err-state").html("An error occurred: " + b);
                    }
                },
                success: function(a) {
                    var e = $.parseJSON(a);
                    if (true == e["success"]) {
                        $("#action").html(e['message']);
                        // here is what you want, callback Php response content in Html DOM
                    }
                }
            });
            return false;
        });

在你的 Php 代码中,只需在任何成功函数之后执行:

if ($result) {
            echo json_encode(array(
                'success' => true,
                'msg' => "Nice CallBack by Php sent to client Side by Ajax Call"
            ));
        }

【讨论】:

  • 如何使用现有的 jQuery 脚本将 Ajax 添加到 PHP 调用脚本?如前所述,我还需要现有的 jQuery 脚本来运行/显示 jQuery 警报消息。
【解决方案2】:

如果您想使用第二遍,您应该使用 jQuery 将数据发布到使用 AJAX 的 PHP 脚本。

http://api.jquery.com/category/ajax/ 有很多关于编写 AJAX 函数和处理返回数据的函数和教程。特别是看post()函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多