首页 文章

Ajax成功没有运行

提问于
浏览
-1

所以我有一个奇怪的问题 . 我在我的机器上做了一个小应用程序工作正常但是当我上传到学校服务器时它停止工作 . 我正在做的是使用ajax访问json数据 . 我已经测试了,我得到了正确的json响应,我正好连接到数据库,并且ajax每两秒运行一次 . 但是ajax成功部分的代码永远不会运行 . 服务器上的数据库与我的机器上的数据库相同,连接已经过故障排除并且运行良好,但仍然无法运行ajax成功代码 . 提前致谢!

setInterval(function () {
            $.ajax({
                type: 'GET',
                url: 'JSONFile.php',
                dataType: 'json',
                success: function (retrieved) {
                    $.each(retrieved, function (index, i) {
                         alert('This line of code is the problem. This alert does not run but should');
                    });
                }
            });
        }, 2000);

2 回答

  • -1

    jQuery 3使用 donefailalways 进行编码

    // Assign handlers immediately after making the request,
    // and remember the jqXHR object for this request
    var jqxhr = $.ajax( "example.php" )
      .done(function() {
        alert( "success" );
      })
      .fail(function() {
        alert( "error" );
      })
      .always(function() {
        alert( "complete" );
      });
    

    https://api.jquery.com/jQuery.ajax/

    弃用通知:从jQuery 3.0开始,jqXHR.success(),jqXHR.error()和jqXHR.complete()回调被删除 . 您可以使用jqXHR.done(),jqXHR.fail()和jqXHR.always()代替 .

  • 0

    如果尚未完成,请确保PHP文件从服务器返回JSON响应 . AJAX设置为使用JSON格式与服务器通信,如果服务器不以这种方式响应,AJAX将不会将响应视为成功 .

    看看Returning JSON from PHP to JavaScript? .

    Update:

    在打开浏览器的开发人员工具时尝试运行以下代码 . 一旦应用程序在断点处停止,请检查浏览器中的 data 并查看您的've got. It is most likely a string in JSON format, that means you will need to parse it to be able to iterate through it'项目 .

    success: function(data){
        debugger; // inspect the returned data
        var obj = JSON.parse(data); // returned data is a string and so, to work on it, it needs to be parsed
        $.each(obj, function (index, i) {
            $('<div class="Post"><h2>' + i.UserName + '</h2><p>' + i.Content + '</p></div>').prependTo($('#MainContent')).fadeOut(1).fadeIn(1000); }
        );
    }
    

相关问题