【发布时间】:2014-03-21 07:39:02
【问题描述】:
我正在使用express,node.js和mysql。在Ajax代码中,成功不起作用。下面是ajax代码。
function GetData_1(){
var state = $("#dpState_1").val();
console.log(state);
$.ajax({
url:"http://localhost:5000/postDistrict",
type: "post",
data: {objectData :state},
dataType: "json",
crossDomain: "true",
success: function (result) {
console.log('Im reaching at the postDistrict');
$.ajax({
url:"http://localhost:5000/getDistrict",
type: "get",
dataType: "json",
crossDomain: "true",
success: function (result) {
console.log("Inside Success")
$.each(result,function(index,obj){
$("#dpDistrict_1").append("<option value = " + obj.dist + ">" + obj.dist+
"</option>"); });
},
error: function (obj, txtStatus, error) {
alert("There was some error,could not fetch data.....");
}
});
},
error: function (obj, txtStatus, error) {
alert("There was some error,could not fetch data... :((");
}
});
}
但是数据(即状态)被发布到所需的 URL。在 node.js 的帮助下,我使用 POST 获取帖子内容,然后使用 GET 将数据放在 HTML 中,代码是下面:
var application_root = __dirname,
express = require("express"),
mysql = require('mysql2');
path = require("path");
var app = express();
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123',
database: "info"
});
app.use(express.bodyParser());
app.use(express.cookieParser('shhhh, very secret'));
app.use(express.session());
// Config
app.configure(function () {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(application_root, "public")));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.post('/postDistrict', function(req, res) {
console.log(req.body.objectData);
var state = req.body.objectData;
app.get('/getDistrict', function(request, response){
res.setHeader('Content-Type', 'application/json');
console.log('select dist from information where state =' +"'"+ state + "'");
connection.query('select dist from information where state =' +"'"+ state +
"'", function(err, rows) {
response.json(rows);
});
});
});
// Launch server
app.listen(5000, function(){
console.log('Server running...');
});
【问题讨论】:
-
如果成功没有触发,那么这意味着您的服务器在处理请求后没有返回状态 200。
-
@setec..我是 node.js 的新手,所以你能告诉我我必须在代码中做什么更新,这样它才能工作......
-
我想知道您是否在那里使用跨域调用,因为您在代码中设置了所需的标志和标题。为了帮助您调试,您应该运行
curl -I http://localhost:5000/getDistrict以获取有关状态代码(状态 200)的更多信息。顺便说一句:您是否为 getDistrict 包含了 GET_Route?因为我在代码中找不到它。如果您不知道如何使用 curl,请尝试在线提供的数十种“http 标头查看器”服务之一。
标签: javascript jquery ajax node.js express