我正在从客户端进行ajax调用。想要将数据(城市的价值)传递给客户端。当我试图在服务器端访问值时,我无法访问其值。这是代码
服务器:
var express = require("express"),
http = require("http"),
bodyParser= require("body-parser"),
yelp = require("yelp"),
app;
// Create our Express-powered HTTP server
/ and have it listen on port 3000
app = express();
http.createServer(app).listen(3000);
// set up a static file directory to use for default routing
app.use(express.static(__dirname));
// set up our routes
// for user login
app.get("/yelp", function (req, res) {
var city = req.query.city;
var yelp = require("yelp").createClient({
consumer_key: "xyz",
consumer_secret: "xyz",
token: "xyz",
token_secret: "xyz"
});
console.log("city="+city);
// See http://www.yelp.com/developers/documentation/v2/search_api
yelp.search({term: "restaurants", location:"fullerton" , limit: 5 }, function (error, data) {
console.log(error);
res.format({
'application/jsonp': function(){
res.send('yelp('+JSON.stringify(data)+');');
}
});
});
});
客户端ajax调用函数:
var main = function () {
"use strict";
var $button= $("#search");
$button.on("click",function(){
var input_city= $("#city").val();
$.ajax({
type: "GET",
url: "/yelp",
data: JSON.stringify({city :input_city }),
jsonpCallback: "yelp",
contentType: "application/jsonp; charset=utf-8",
dataType: "jsonp"
/* success: function(msg){
console.log("success called");
var $result = $.parseJSON(msg);
console.log($result.businesses[0].name);
$('#list').append("<div>"+$result.businesses[0].name+" </div>");
},
error: function (errormessage){
console.log("error called");
$('#list').append(errormessage);
}*/
})
.done(function (data,status){
$('#list').html("");
var i = 0;
for(i=0; i < data.businesses.length; i++)
{
$('#list').append("<div class='business'>");
$('#list').append("<div class='business_name'>");
$('#list').append(data.businesses[i].name);
$('#list').append("</div>");
$('#list').append("<div class='business_address'>");
$('#list').append(data.businesses[i].location.display_address);
$('#list').append("</div>");
$('#list').append("<div class='business_phone'>");
$('#list').append(data.businesses[i].phone);
$('#list').append("</div>");
$('#list').append("<div class='business_rating'>");
$('#list').append(data.businesses[i].rating);
$('#list').append("</div>");
$('#list').append("</div>");
}
})
.fail(function (data, status){
console.log("fail called");
console.log(data);
console.log(status);
});
});
};
服务器端控制台的输出 city = undefined
答案 0 :(得分:-1)
您的服务器实际上期望city
成为查询字符串。在您的客户端,请执行:
url: "/yelp?city=" + input_city,
并删除data:...
行。