简体   繁体   English

jQuery解析Ajax响应

[英]jquery parse ajax response

I'm using Jquery's ajax method, and I need help parsing data coming back from backend server. 我正在使用Jquery的ajax方法,并且我需要解析从后端服务器返回的数据的帮助。

server response will be either "valid" or "not valid. 服务器响应将为“有效”或“无效”。

Currently my "if statement logic is not working, this is what I have tried so far). 目前,我的“如果语句逻辑无法正常工作,这是我到目前为止已经尝试过的方法)。

$.ajax({
    url: 'php/phone-valid.php',
    type: 'POST',
    data: {userid: $.trim($('#userid').val())},
    success: function(data) {
        console.log(data);

        if (result.indexOf("not valid")) {
            ("#mustbevalid").val("You must validate your phone number");
            console.log("Phone hasn't been validated");
            e.preventDefault();
        };
    }
});

Your help is highly appreciated. 非常感谢您的帮助。

You're checking result.indexOf , but your response data is in data not result . 您正在检查result.indexOf ,但是您的响应数据在data而不是result Additionally, indexOf returns the position, which could be 0. So change to: 此外,indexOf返回位置,该位置可以为0。因此更改为:

if(data.indexOf("not valid") > -1) {

Side note: this method of checking a result is error-prone and usually undesirable. 旁注:这种检查结果的方法容易出错,通常是不可取的。 It would be better for you to output a JSON object with a success property. 最好输出具有成功属性的JSON对象。

Example success response: 成功响应示例:

echo json_encode(array('success' => true));
// Outputs: {"success":true}

Example error response: 错误响应示例:

echo json_encode(array('success' => false));
// Outputs: {"success":false}

Now, you can parse the JSON: 现在,您可以解析JSON:

$.ajax({
    ...
    dataType : 'json', // <-- tell jQuery we're expecting JSON
    success: function(data) {
        if (data.success) {
            // success
        } else {
            // error
        };
    }
});

indexOf will return the position in the string. indexOf将返回字符串中的位置。 So use this instead: 所以改用这个:

if(data.indexOf("not valid") == 0) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM