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 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据