【问题标题】:AJAX success callback alert not working?AJAX 成功回调警报不起作用?
【发布时间】:2014-08-13 04:20:00
【问题描述】:

我查看了关于 SO 的其他各种帖子,但我似乎没有发现问题所在,希望您能帮助我阐明这个问题。基本上,我正在做一个微博应用程序并在单击按钮时插入一条推文,这会调用 jQuery ajax 函数。这是各自的代码:

home.js

这是 ajax jquery 调用

function sendTweet(single_tweet) {
var tweet_text = $("#compose").val();

tweet_text = tweet_text.replace(/'/g, "'");
tweet_text = tweet_text.replace(/"/g, """); 

var postData = {
    author      :   $("#username").text().split("@")[1],    // be careful of the @! - @username
    tweet       :   tweet_text,
    date        :   getTimeNow()
};

$.ajax({
    type        :   'POST',
    url         :   '../php/tweet.php', 
    data        :   postData,
    dataType    :   'JSON',
    success     :   function(data) {
        alert(data.status);
    }
})
}

ajax调用成功,推文被插入,但是我无法在success参数下得到alert调用fireback。我尝试了一些基本的东西,比如alert('abc');,但也没有用。

tweet.php

这只是一个包装器,看起来像这样:

<?php
include 'db_functions.php';

$author = $_POST['author'];
$tweet  = $_POST['tweet'];
$date   = $_POST['date'];

insert_tweet($author, $tweet, $date);

$data = array();
$data['status'] = 'success';
echo json_encode($data);
?>

这只是将推文插入数据库,我想尝试发送简单的 JSON 格式的数据,但 data.status 对成功回调不起作用。

db_functions.php

这就是 insert_tweet 函数所在的地方,它看起来像这样:

function insert_tweet($author, $tweet, $date) {
global $link;
$author_ID = get_user_ID($author);
$query =    "INSERT INTO tweets (`Author ID`, `Tweet`, `Date`) 
            VALUES ('{$author_ID}', '{$tweet}', '{$date}')";
$result = mysqli_query($link, $query);
}

我已经对其进行了测试,我很确定它运行良好。我怀疑这是问题的原因,但如果是的话,我会全神贯注。我已经测试了$link,它是在db_functions.php 文件顶部包含的另一个文件中定义的,并且可以正常工作。

不胜感激有关此的一些建议,谢谢!

更新

success 更改为complete,它可以工作。但是,data 对象似乎有点奇怪:

data.status在alert中弹出200

我尝试在PHP中将JSON数组元素名称更改为data['success'],并在前端使用data.success访问它,并在警告框中输出:

function () {
            if ( list ) {
                // First, we save the current length
                var start = list.length;
                (function add( args ) {
                    jQuery.each( args, function( _, arg ) {
                        var type = jQuery.type( arg );
                        if ( type === "function" ) {
                            if ( !options.unique || !self.has( arg ) ) {
                                list.push( arg );
                            }
                        } else if ( arg && arg.length && type !== "string" ) {
                            // Inspect recursively
                            add( arg );
                        }
                    });
                })( arguments );
                // Do we need to add the callbacks to the
                // current firing batch?
                if ( firing ) {
                    firingLength = list.length;
                // With memory, if we're not firing then
                // we should call right away
                } else if ( memory ) {
                    firingStart = start;…

这是什么意思??

更新 2

好的,我不知道这是否有帮助,但我已经从 Chrome 的检查器中打印了控制台日志,如果我没记错的话,JSON 数据会很好地发回。这是整个日志:

Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
abort: function ( statusText ) {
always: function () {
complete: function () {
arguments: null
caller: null
length: 0
name: ""
prototype: Object
__proto__: function Empty() {}
<function scope>
done: function () {
error: function () {
fail: function () {
getAllResponseHeaders: function () {
getResponseHeader: function ( key ) {
overrideMimeType: function ( type ) {
pipe: function ( /* fnDone, fnFail, fnProgress */ ) {
progress: function () {
promise: function ( obj ) {
readyState: 4
responseJSON: Object
    status_success: "success"
    __proto__: Object
    responseText: "{"status_success":"success"}"
    status_success: "success"
__proto__: Object
responseText: "{"status_success":"success"}"
setRequestHeader: function ( name, value ) {
state: function () {
status: 200
statusCode: function ( map ) {
statusText: "OK"
success: function () {
then: function ( /* fnDone, fnFail, fnProgress */ ) {
__proto__: Object
__defineGetter__: function __defineGetter__() { [native code] }
__defineSetter__: function __defineSetter__() { [native code] }
__lookupGetter__: function __lookupGetter__() { [native code] }
__lookupSetter__: function __lookupSetter__() { [native code] }
constructor: function Object() { [native code] }
hasOwnProperty: function hasOwnProperty() { [native code] }
isPrototypeOf: function isPrototypeOf() { [native code] }
propertyIsEnumerable: function propertyIsEnumerable() { [native code] }
toLocaleString: function toLocaleString() { [native code] }
toString: function toString() { [native code] }
valueOf: function valueOf() { [native code] }
get __proto__: function __proto__() { [native code] }
set __proto__: function __proto__() { [native code] }

更新 3

控制台错误截图

【问题讨论】:

  • 有错误日志吗?当您在浏览器中使用开发人员工具时,从服务器返回的内容是什么?
  • 签入错误块。
  • @JeremyMiller 抱歉,我对错误日志不太熟悉 - 你的意思是 console.log(data) 之类的吗?

标签: javascript php jquery ajax twitter


【解决方案1】:

试试这个:

$.ajax({
    type        :   'POST',
    url         :   '../php/tweet.php', 
    data        :   postData,
    dataType    :   'json',
    complete     :   function(data) {
        alert(data.status);
    }
})

【讨论】:

  • 我试过了,它似乎可以工作,但 data.status 似乎覆盖了从 PHP 文件回显的 data['status'] JSON 数据,它显示 200。200 是什么?
  • 我认为您对 JSON 使用了错误(或否)引号。您必须使用双引号(用于属性名称和字符串值)
  • 如果你指的是tweet.php文件中的$data["success"] = "success";这一行,我改变了它,它仍然输出我在上面更新中发布的那个奇怪的函数。我不确定它来自哪里......
  • 好的,我知道函数来自哪里,它是作为返回的 JSON 对象的一部分的状态代码。但即使我将它更改为另一个变量,如成功,并像data.success 一样访问它,它也不起作用。获取undefined。想知道为什么?
【解决方案2】:

试试下面的代码。我在向服务器发送数据时添加了内容类型,成功方法中的 parseJson 方法,

$.ajax({
         url: "../php/tweet.php",
         data: '{"author": "' + $("#username").text().split("@")[1] + '","tweet": "' + tweet_text + '","date": "' + getTimeNow() + '"}',
         dataType: "json",
         contentType: "application/json; charset=utf-8",
         type: "POST",
         success: function (data) {
             var myResult = $.parseJSON(data);
         },
         error: function (err) {
                alert(err)
         }
      });

如果您有任何澄清可以通过jquery ajax文档

注意:如果你为错误方法添加回调对你有帮助

【讨论】:

  • data.d 中的“d”是什么?
  • 嗯...我尝试了您的建议,但似乎没有用。控制台抛出错误“caught unknown object u”。
  • 不需要d,它指的是C#输出。你能把你的错误截图和关于服务器响应的信息放上去吗?
  • 直接查看成功消息,不用像“var myResult = data”这样的parseJSON方法;console.log(data)
  • 哦,我去掉了 parseJSON(data) 行,成功消息包含在 UPDATE 2 中。
【解决方案3】:

尝试在您的 PHP 文件中设置内容类型:

header( 'Content-Type: application/json' );

然后回显您的数据:

echo json_encode( $data );

并停止脚本:

exit;

希望对你有帮助!

【讨论】:

    【解决方案4】:

    尝试将您的输入类型从“提交”更改为“按钮”。 我希望它有效。

    【讨论】:

    • 欢迎来到 SO。如果你认为你有解决方案,你应该发布工作代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-30
    • 2014-07-08
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多