【问题标题】:Jquery $.post not working as expectedJquery $.post 没有按预期工作
【发布时间】:2015-06-10 14:05:12
【问题描述】:

我正在使用 PHPJQueryMongoDB 创建一个 Web 应用程序,但在使用 $.post 时遇到了一些问题。我有一个带有表格的页面,其中每一行都由用 CSS 设计的自定义按钮标记。我使用以下脚本获取该按钮的索引并将其传递给 PHP 文件。这将获得正确的索引并将其发布到文件中就好了。

<script>
$(".completed").click(function() {
    var index = $(".completed").index(this);
    $.post("lock.php", {position: index});
});
</script>

lock.php 应该将此索引放入会话变量中并加载一个名为 display_page.php 的新页面,但 display_page 永远不会被加载,并且 Firebug 中不会显示任何错误。我试过直接发帖到display_page,但这并没有改变任何东西。这是我的 lock.php 的样子:

<?php
   $pos = $_POST['position'];
   session_start();
   $_SESSION['index'] = $pos;
   header('Location: display_page.php');
?>

如果有人能指出我正确的方向,我将不胜感激。

【问题讨论】:

  • 查看代码中突出显示的语法。
  • @anantkumarsingh 这并没有改变任何东西,但现在我注意到我的帖子有 302 错误
  • 您在lock.php 中的header('Location: display_page.php'); 不会重定向您的$.post() 呼叫页面。您需要在 $.post()success 上使用 javascript 重定向
  • 您不能在 ajax 调用中使用 header() 重定向。您需要改用 javascript 重定向。
  • 我尝试使用 $location.attr('href',url);而不是 lock.php 中的 header(),现在 lock 有 200 个代码,并且 display_page 永远不会被调用

标签: javascript php jquery mongodb


【解决方案1】:

您需要执行以下操作:-

<script>
    $(".completed").click(function() {
       var index = $(".completed").index(this);
       $.post("lock.php", {position: index},function( data ){ 
            if(data == 'success'){ // check the response
                window.location.href = 'display_page.php'; // if response is success then redirect to the page
            }else{
              // some alert message
            }
       });
    });
    </script>

在php页面中:-

<?php
   session_start(); // first write this session start code
   if(isset($_POST['position'])){ // check values are coming or not
    $pos = $_POST['position'];
    $_SESSION['index'] = $pos;
    echo "success"; // return success to ajax
   }else{
       echo "failure"; // return failure to ajax
   }
 ?>

【讨论】:

  • 这对我没有任何作用,它现在甚至没有发布
  • if(data = 'success') 应该是if(data == 'success')
  • 是的,很抱歉这个错误。我编辑了那个。谢谢@肖恩
  • 哦,哇,我应该已经抓住了。我最终将它与下面的弗朗西斯罗德里格斯的回应结合起来。
  • @php-新手。感谢您的标记。我还检查了我的代码。它非常适合我。
【解决方案2】:

你有很多不同的回调:

var jqxhr = $.post( "example.php", function() {
  alert( "success" );
})
  .done(function() {
    alert( "second success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
});

jqXHR 对象

http://api.jquery.com/jquery.post/#jqxhr-object

【讨论】:

    猜你喜欢
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    • 2019-07-13
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多