weixin_33694172 2017-05-04 07:55 采纳率: 0%
浏览 35

jQuery Ajax发布未定义

I've been searched about this problem over stackoverflow, but couldn't get any answer that solves my problem.

This is even sample code in my node.js book. I don't know why this is not working and I want to sue author of this book. He gave me lot of stress.

1] Code in server.js

app.post('/products', function (request, response){

console.log(request.params);
var name = request.params.name;
var price = request.params.price;
var item = {
    name : name,
    price : price
};

items.push(item);

response.send({
    message : 'Data pushed',
    data : item
    });
});

2] Code in index.html

$('#post').click(function(){
     console.log($('#name').val());
     console.log($('#price').val());
     $.ajax({
        url:'/products',
        type:'post',
        dataType : 'text',
        data : {
          name : $('#name').val(),
          price : $('#price').val()
        },
        success : function(data){
          $('#output').val(data);
        }
    });
});

I can see correct data which I put in #name and #price in console of Chrome browser by console.log. But I can't see any data in server.js by console.log(request.params). console.log(request.params), console.log(request.params.id), console.log(reqeust.params.price) all returns 'undefined' Why does it return undefined? I tried lots of things I searched through internet, but nothing solved. What's the problem?

  • 写回答

1条回答 默认 最新

  • weixin_33704591 2017-05-04 08:00
    关注

    Did you used Expess in you server file?

    var app = express();
    app.use(express.bodyParser());
    

    Or

    var bodyParser = require('body-parser');
    app.use(bodyParser.json()); // for parsing application/json
    app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
    

    In server js you need to use request.body instead of request.params like,

    var name = request.body.name;
    var price = request.body.price;
    

    You are sending json from server so use dataType : 'json' like,

    $.ajax({
        url:'/products',
        type:'post',
        dataType : 'json', // use json instead of text
        data : {
          name : $('#name').val(),
          price : $('#price').val()
        },
        success : function(data){ 
            console.log(data);// for name use data.data.name
            //$('#output').val(data);
        }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛