【问题标题】:jQuery $.post not working on specific condtionsjQuery $.post 在特定条件下不起作用
【发布时间】:2015-12-02 11:03:25
【问题描述】:

我正在尝试使用 AJAX 和 jQuery $.post 将一些数据插入到 mySQL 数据库中。我的功能测试尝试如下

index.html:代码片段(已经在许多其他功能中使用 jQuery)

$.post( 
    "updateDatabase.php",
    { name: "Zara" },
    function(data) {
         //$('#stage').html(data);
         alert('Success');
    }
);

updateDatabase.php

<?php
if( $_REQUEST["name"] ) {

   $name = $_REQUEST['name'];
   echo "Welcome ". $name;
   echo "<script>alert('Im here')</script>";
}
?>

我得到的是一个“成功”的警报,没有别的(它是 $.post 的回调函数)。我已经研究了很多,发现了一些相似但不同的问题。但是我的问题没有解决,因为这个特定问题没有令人满意的解决方案。

【问题讨论】:

  • ajax调用不像import,updateDatabase.php中的数据以成功函数的data变量的形式传递给ajax
  • 好的。现在我明白了这个概念。我想我必须使用数据变量来获取输出。
  • 你说得对,看我的回答

标签: javascript php jquery mysql ajax


【解决方案1】:

您正在回显一个字符串echo "alert('Im here')";。所以,

  1. 不能将其视为 javascript 函数。
  2. 您没有在成功回调中使用响应。

你可以做的是:

function(data) {
     alert('Success: '+data);
     // outputs: Success: Welcome Zara I'm here
}

在 php 处:

echo "Welcome ". $name . " I'm here";

【讨论】:

  • 现在我知道我犯的错误了。对不起。这是我的第一个 $.post。
  • @danimvijay 不用担心,当您是新手时,它会发生在这里。
【解决方案2】:

尝试使用 json 作为返回数据的安全方式

$.post( 
    "updateDatabase.php",
    { name: "Zara" },
    function(data) {//data is all the echoed text from the updateDatabase.php in our case a json string
         alert(data.message);
    }
);

<?php
if( $_REQUEST["name"] ) {

   $name = $_REQUEST['name'];
   echo json_encode([message =>"Welcome ". $name])

}
?>

【讨论】:

    【解决方案3】:

    改变这个

    echo "alert('Im here')";
    

    echo "Im here";// no need of alert.
    
    function(data) {
         alert(data);
               ^// will alert Im here
    }
    

    你也可以使用

    .done(function() {
        alert("Success");
    })
    

    最终代码

    $.post( "example.php", function() {
       alert( "success" );
    })
    .done(function() {
        alert( "second success" );
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-15
      • 1970-01-01
      • 2011-11-03
      • 2023-03-30
      • 1970-01-01
      • 2012-01-11
      • 2014-11-29
      • 2011-02-01
      相关资源
      最近更新 更多