简体   繁体   English

无法从ajax请求中的php获得返回

[英]Unable to get the return from php in ajax request

I just want to get back some return value from the ajax data post. 我只想从ajax数据帖子中获取一些返回值。 I am not sure why I am not getting something back in success. 我不确定为什么我没有获得成功。 Please review the code and tell me where I am wrong 请查看代码,并告诉我我错了

My jquery code 我的jQuery代码

$("#btnlogin").click(function(){

    var email = $("#emaillog").val();
    var password = $("#passlog").val();
    console.log('test');
    /* $.ajax({
        url: 'home2/login_user',
        //data: {'title': title},  change this to send js object
        type: "post", 
        data: 'email=' + email+'&password='+password,
        success: function(output) {
            url:"home2/login_user",
            data: 'email=' + email+'&password='+password,
            alert(output);
        }
    });*/

    $.ajax ({
         url:"home2/login_user",
         type: "post",
         dataType: 'json', 
         data: 'email=' + email+'&password='+password,
         success: function (data) {
             $.each(data, function(key, value) {
                 console.log(key,'--',value);
             });
              //iterate here the object
         }
     });
}); 

My php code 我的PHP代码

public function Login_user()
    {
        $email = $this->input->post('email');
        $password = $this->input->post('password');
        $data['result'] = $this->Home_model->login_to_user($email,$password); 
        echo json_encode ($data['result']);     


    }

In php code I echo the result but in in jquery. 在php代码中,我在jQuery中回显结果。 I am not getting any result in success 我没有取得任何成功的结果

Thanks 谢谢

use parseJSON 使用parseJSON

var obj = jQuery.parseJSON(data);
console.log(obj.key);

The reason is because your backend code does not seem to be able to find the username and password parameters. 原因是因为您的后端代码似乎无法找到用户名和密码参数。 You're passing them the wrong way at this line of code: 您在以下代码行中以错误的方式传递了它们:

data: 'email=' + email+'&password='+password,

Replace the string with a JavaScript object: 将字符串替换为JavaScript对象:

data: { email: email, password: password }

well, first, you are passing the parameters like it was a get request, and its not. 好吧,首先,您传递的参数就像是一个get请求,而不是它。

Change the way you passing to something like this. 更改传递给类似内容的方式。

 $.ajax ({
         url:"home2/login_user",
         type: "post",
         dataType: 'json', 
         data: { field1: "hello", field2 : "hello2"},
         success: function (data) {
             $.each(data, function(key, value) {
                 console.log(key,'--',value);
             });
              //iterate here the object
         }
     });

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

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