通过来自Node.js的HTTP响应中的AJAX接收请求中发送的数据

时间:2015-09-21 16:56:22

标签: javascript node.js http express xmlhttprequest

我通过循环遍历拆分字符串发送多个AJAX请求。我需要将响应与请求相关联。我试图在HTTP响应中接收AJAX请求中提供的数据。我需要这个,因为我正在发出多个请求,并且响应异步回来。似乎不推荐使用AJAX的同步功能。

我的javascript:

var ingredientName = "";
var regExpNumber = /\d+/;
var inputRecipe = $('#addRecipe fieldset input#inputRecipeIngredients').val();

//split up the string into pieces for analysis and matching   
var recStringArray = inputRecipe.split(/[ ,]+/);
//need to do some kind of error checking in the future

//step through each piece of the string
for(var i=0; i < recStringArray.length; i++) { 
    //check each array item for numbers 
    var volumeCheck = (recStringArray[i].match(regExpNumber));

    //Check each array item that isn't a number to see if it is a unit of measure
    if (volumeCheck == undefined) {
        $.ajax({
            type: 'POST',
            url: '/recipes/uomsearch/' + recStringArray[i],
            data: { 'key' : recStringArray[i]}
        }).done(function( response1, response2 ) {
            // Check for a successful (blank) response
            if (response1.length == 0) {
                console.log("didn't find UOM");
                ingredientName += response2;
                console.log(ingredientName);               
            }
            else {
                for(var y=0; y < response1.length; y++) {
                    var p = response1[y].root;
                    console.log(p);
                }   
            }
            });
    }//end of uom check for non-number array items
}

我的recipes.js服务器上运行的代码:

router.post('/uomsearch/:key', function(req, res, res2) {
    var db = req.db;
    var collection = db.get('uomlist');
    var query = req.params.key

    res2 = query;
        console.log(res2);
    collection.find({'key': query},{},function(e,docs){
        res.json(docs);
    });
});

1 个答案:

答案 0 :(得分:0)

在代码中添加“async:false”会导致代码在继续之前阻塞并等待响应。这使我能够捕获数组的索引并存储数据。

$.ajax({
        type: 'POST',
        url: '/recipes/uomsearch/' + recStringArray[i],
        data: { 'key' : recStringArray[i]},
        async: false
 })