Convert ajax response array object to javascript a

2019-08-02 06:23发布

问题:

I am using ajax to submit a login form in Yii. Here is my ajax function:

$("#login-form").submit(function() {

        var email = $("#email").val();
        var password = $("#password").val();

        $.ajax({
            url: "<?php echo Yii::app()->request->baseUrl; ?>/site/validatelogin",
            type: "post",
            data: "email=" + email + "&password=" + password,
            success: function(response) {
                if (response === "1") {
                    window.location.href = "<?php echo Yii::app()->getBaseUrl(true); ?>/dashboard";
                }
                else
                {
                    //Dispaly response errors above login form
                }
            },
            error: function() {
                alert("Could not perform the requested operation due to some error.");
                return false;

            }
        });

    });

My PHP controller function is validatelogin as follows:

 $email = $_POST['email'];
    $password = $_POST['password'];


    $model = new LoginForm();

    $model->email = $email;
    $model->password = $password;


    if ($model->validate() && $model->login()) {
        echo "1";
    } else {
        print_r($model->getErrors());
    }

If the user enters correct credentials I send 1 as response to view and user is redirected to dashboard.

But if user enters incorrect credentials then different errors are received in ajax response depending upon the type of error.

I want to display those errors above login form in else part of success function through a loop.

But when I run the loop over response then that array has very large length i.e for example if the error in response was "Incorrect password" then the response array has length of 18(the number of characters) in the error message. In short the response array is like:

array('I','n','c','o','r','r'....)

rather than

array([0]=>"Incorrect password")

How do I convert response array in the latter format and iterate over each index to display error message to the user above the login form?

回答1:

Encode it to JSON.

In your php:

echo json_encode($model->getErrors());

In your js (in the else):

var errors = $.parseJSON(response);

Edit:

In your case it would be better to always return JSON.

Your JS could be changed to:

var jqxhr = $.post("<?php echo Yii::app()->request->baseUrl; ?>/site/validatelogin", {
    email: email,
    password: password
}, 'json');
jqxhr.done(function(response) {
    if (response.valid) {
        window.location.href = "<?php echo Yii::app()->getBaseUrl(true); ?>/dashboard";
    } else {
        if (response.errors) {
            ...
        }
    }
});
jqxhr.error(function(response) {
    alert("Could not perform the requested operation due to some error.");
});

Your PHP:

$response = array('valid' => false);
if ($model->validate() && $model->login()) {
    $response['valid'] = true;
} else {
    $response['errors'] = $model->getErrors();
}
header('Content-type: application/json');
echo json_encode($response);


回答2:

In addition to @sroes's answer, use Yii library for JSON

echo CJSON::encode($response);

instead of

echo json_encode($response);

why ?

Why use CJSON encode when we have json_encode