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

时间:2016-06-03 13:37:16

标签: javascript php jquery ajax

我只想从ajax数据帖子中获取一些返回值。我不确定为什么我没有取得成功。请查看代码并告诉我错误的地方

我的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
         }
     });
}); 

我的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']);     


    }

在php代码中我回显结果但是在jquery中。我没有取得任何成功的结果

由于

3 个答案:

答案 0 :(得分:1)

使用parseJSON

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

答案 1 :(得分:1)

原因是您的后端代码似乎无法找到用户名和密码参数。你在这行代码中以错误的方式传递它们:

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

用JavaScript对象替换字符串:

data: { email: email, password: password }

答案 2 :(得分:0)

好吧,首先,你传递的参数就像是get请求,而不是。

改变你传递给这样的东西的方式。

    var express = require('express')
  , others = require('./app_server/routes/others')
  , locations = require('./app_server/routes/locations')
  , routesApi = require('/app_api/routes/index')
  , ;

require('./app_server/models/db')

var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/app_server/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

// Routes
// LOCATION PAGES
app.get('/', locations.homeList);
app.get('/location', locations.locInfo);
app.get('/location/review/new', locations.addReview);
// OTHER PAGES
app.get('/about', others.about);

app.listen(3000, function(){
  console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});