issue with jquery promises

issue with jquery promises

本文关键字:promises jquery with issue      更新时间:2023-09-26

我正在练习jquery promise,在我的演示代码中发生了一些奇怪的事情。我的代码所做的是,当我点击按钮时,它会从服务器接收一个简单的json数据。我使用两个jquery承诺,一个是done(),第二个是fail()。当我点击按钮时,它从服务器接收数据,但done()没有执行,数据通过fail()显示在控制台中。为什么以及如何解决此问题?以下是我的代码

jquery

        var Obj = function () {
            return {
                gets: function (successHandler, errorHandler) {
                    console.log('hello');
                    return $.ajax({
                        url: '/server.php',
                        dataType: 'JSON',
                        type: 'GET'
                    });
                }
            }
        };
        $('.button').on('click', function () {
            var obj = new Obj();
            var promise = obj.gets();
            promise.done(function (data) {
                console.log(data);
            });
            promise.fail(function (e) {
                console.log(JSON.stringify(e)); //this logs below
            });

输出

{"readyState":4,"responseText":"<?php'n$response = array('oranges', 'apples', 'berries');'nexit(json_decode($response));","status":200,"statusText":"OK"} 

这是我的php代码

$response = array('oranges', 'apples', 'berries');
exit(json_decode($response));
return $.ajax({
   url: '/server.php'
   dataType: 'JSON',
   ...

但是

"responseText":"<?php'n$response = array ...

jQuery期望JSON,但服务器提供PHP源。因此抛出解析异常,拒绝Deferred并调用.fail()