【问题标题】:Phonegap returns object Object but echo correct dataPhonegap 返回对象 Object 但回显正确的数据
【发布时间】:2019-03-29 05:46:40
【问题描述】:

我在服务器端使用PhoneGap 和PHP 制作手机应用程序。 Login 函数一直运行良好,但 AJAX 返回错误 [object Object] 而 PHP 返回 JSON 中的正确值。

它用于为现有网站制作手机应用程序并使用其数据库。 我的 PHP 打印的数据是正确的,但我收到了来自 ajax 的错误响应。 警报(响应)
出错时返回 [object Object] 值

每当我尝试 警报(response.val) 我奇怪的是不确定,但在网络中,我可以看到打印的数据在 JSON 中是正确的。

 {{"user_id":"390","response":"Success"}}

但是当我在浏览器上查看控制台时,我看到了一个意外错误。

 Unexpected parameter ':'

我的ajax函数如下

$(document).ready(function () {
    $("#btnLogin").click(function () {
        var gebr = $("#login_username").val().trim();
        var pass = $("#login_password").val().trim();
        var dataString = "username=" + gebr + "&password=" + pass + "&login=";
        var msg = "";
        $("#message").html("Authenticating...");

        if (gebr != "" && pass != "") {
            $.ajax({
                type: "POST",
                data: dataString,
                dataType: "json",
                //contentType: "application/javascript",
                crossDomain: true,
                url: "http://url/page/app/index.php?&jsoncallback=?",
                headers: "application/json",
                success: function (response) {
                    var user_id = response.user_id;
                    var success = response.response;
                    localStorage.setItem("user_id", user_id);
                    window.location = "home.html";
                    alert("login successfull");
                },
                error: function (response) {
                    $("#message").html("error..");
                    alert(response);
                }
            });
        } else {
            msg = "Please fill all fields!";
            $("#message").html(msg);
        }
        return false;
    });

PHP

header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');


$gebruikersnaam = $_REQUEST['username'];
$wachtwoord = md5($_REQUEST['password']);
$user = [];


//if user and password are filled
if (!empty($gebruikersnaam) && isset($wachtwoord)) {
//checks if user_id has been found
if (!$found_user_id) { 
    $msg = "user not found!";
    print json_encode($msg);
} else {
    if (($gebruikersnaam == $user['gebruikersnaam'] && $wachtwoord == $user['wachtwoord']) && ((!empty($user['single_allowed_ip_address_for_login']) && $user['single_allowed_ip_address_for_login'] == $_SERVER['REMOTE_ADDR'])|| empty($user['single_allowed_ip_address_for_login']))) {
        //responds with this data
        $user_id = $user['user_id'];
        $response[] = array(
            'user_id' => $user_id,
            'response' => 'Success'
        );
        print json_encode($response);       
    } else {
        $msg = "user is incorrect";
        print json_encode($msg);
    }
  }
}

我一直希望获得成功的响应并将 user_id 保存在本地存储中,以便可以在不同的页面上使用它。

编辑: 在响应中使用 console.log 后,我得到了一个奇怪的对象。

​
     abort: function abort()​
     always: function always()​
     catch: function catch()​
     done: function add()​
     fail: function add()​
     getAllResponseHeaders: function getAllResponseHeaders()​
     getResponseHeader: function getResponseHeader()​
     overrideMimeType: function overrideMimeType()​
     pipe: function pipe()​
     progress: function add()​
     promise: function promise()
​
     readyState: 4
​
     setRequestHeader: function setRequestHeader()​
     state: function state()
​
     status: 200
​
     statusCode: function statusCode()
​
     statusText: "load"
​
     then: function then()​
     <prototype>: {…

这很奇怪,因为这些功能都没有实现,我唯一能识别的是状态码。

【问题讨论】:

  • 请注意您的响应是双包装数组,为什么?你想在哪里做response.val
  • 您无法提醒对象类型的数据。您需要使用 console.log() 或者您必须定义对象的属性.. example var a = [{'user1':{'id':1,'age':24},{'user2': {'id':2,'年龄':44} }];你不能alert(a),但你可以console.log(a)。你也可以alert(a.user1.age);如果上面的对象中不存在user1你会得到一个错误..
  • JSON 对象“{{"user_id":"390","re​​sponse":"Success"}}" 错误。它应该像浏览器端的 [ {"user_id":"390","re​​sponse":"Success"}] 或 {"res":{"user_id":"390","re​​sponse":"Success"}}
  • 双包装数组是因为我将 $response 放入了一个数组中。无论是删除它还是将其更改为 $response["response"] 都不会改变结果。我仍然得到一个对象对象错误。同样在对响应使用console.log 之后,我扫描看到它返回的对象是整个POST。带有状态码、中止、总是、捕获、完成、失败功能(甚至没有使用)。

标签: php jquery ajax phonegap


【解决方案1】:

您需要更正 JSON。 {{"user_id":"390","response":"Success"}} 不是有效的 JSON。必须是{"user_id":"390","response":"Success"}

您在 console.log 中得到了一个奇怪的对象,因为您在 error: function (response)... 中的 response 实际上是 jqXHR jQuery 对象,并且不会直接在其参数中返回您的响应。坚持使用success: function(response)... 并输出服务器发回的任何内容。

【讨论】:

    猜你喜欢
    • 2019-11-22
    • 1970-01-01
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多