如何使用jQuery将变量发布到PHP?

时间:2014-03-30 13:54:32

标签: javascript php jquery

我想使用jQuery将变量发布到PHP页面,然后重定向该PHP页面并回显发布的变量。

HTML:

$(document).ready(function() {
$('.restauarnt_result').click(function() {
    var RestName = $('#restauarnt_name', this).html();
            $.post('restauarnt.php', { RestName : RestName } );
            window.location = 'restauarnt.php';
});
});

点击$('.restauarnt_result')后,自动重定向到'restauarnt.php'网址并回显发布的数据。

PHP:

<?php
   echo $_POST['RestName'];

4 个答案:

答案 0 :(得分:1)

Ajax的目的是与服务器进行通信,而不用离开当前页面。

由于您想要离开当前页面,请不要使用Ajax。

创建表单并提交。

var f = jQuery("<form>", { action: 'restauarnt.php', method: 'post' });
f.append(
    jQuery("<input>", { type: "hidden", name: "RestName", value: RestName })
);
jQuery(document.body).append(f);
f.submit();

答案 1 :(得分:1)

如果你马上要重定向

,使用ajax没什么意义
<form method="post" action="restauarnt.php">
<input name="RestName"/>
<input type="submit"/>
</form>

restauarnt.php

<? 
echo $_POST['RestName'];

答案 2 :(得分:0)

在PHP端使用会话:

<?php
session_start();
// store session data
$_SESSION['RestName']= "RestName";
?>

重新加载后,此值将出现在新的会话变量中。

答案 3 :(得分:0)

您应该在通话结束后重定向。试试这个 -

$.post('restauarnt.php', { RestName : RestName }, function(data){
   // here the call is completed
   console.log(data); // this will print the values echo by the php
   window.location = 'restauarnt.php';
} );