将ajax数据传递到后端javascript

将ajax数据传递到后端javascript,javascript,html,node.js,ajax,Javascript,Html,Node.js,Ajax,我正试图使用一些从网上收集的Ajax代码记录我的用户位置。我试图将其传递到后端代码,在那里我可以将数据存储在我的数据库中进行分析。我以前从未使用过Ajax,也不熟悉传递到后端的语法 这是我的密码 国家: 声明: 城市: $.ajax({ url:“https://geoip-db.com/jsonp", jsonpCallback:“回调”, 数据类型:“jsonp”, 成功:功能(位置){ $(“#country”).html(location.country_name); $(“#state

我正试图使用一些从网上收集的Ajax代码记录我的用户位置。我试图将其传递到后端代码,在那里我可以将数据存储在我的数据库中进行分析。我以前从未使用过Ajax,也不熟悉传递到后端的语法

这是我的密码

国家:
声明:
城市:
$.ajax({
url:“https://geoip-db.com/jsonp",
jsonpCallback:“回调”,
数据类型:“jsonp”,
成功:功能(位置){
$(“#country”).html(location.country_name);
$(“#state”).html(location.state);
$(“#city”).html(location.city);
}
});

我基本上需要通过
$('#country').html(location.country_name)$(#state').html(location.state)$(#city').html(location.city)到我的节点代码。我以前在js中使用过fetch,但不确定这是否是包含Ajax代码的语法。感谢您的帮助。

如果您有一些数据要使用AJAX发送到服务器,并且如果您有类似HTML的内容,您可以很好地使用元素的
textContent
.text()
(使用jQuery)。这是你怎么做的

//正在向服务器发送数据。。。
风险值数据={
国家:$(“#国家”).text(),
州:$(“#州”).text(),
城市:$(“#城市”).text()
};
log(“要发送的数据!”);
控制台日志(数据);
log(“序列化数据!”);
console.log($.param(数据));
//将数据发送到端点并获取JSON值。
$.getJSON(“/endpoint?”+$.param(数据),函数(res){
控制台日志(res);
});

国家:印度
州:泰米尔纳德邦

City:Chennai
对于其他正在查看此问题的人,您也可以在Ajax函数中使用javascript。这可能不是正确的方法,但确实有效

<script>
    $.ajax({
    url: "https://geoip-db.com/jsonp",
    jsonpCallback: "callback",
    dataType: "jsonp",
    success: function( location ) {
    $('#country').html(location.country_name);
    $('#state').html(location.state);
    $('#city').html(location.city);
    
    console.log(location)
    var locaionValues = location;
    var countryNameLocation = location.country_name;
    var stateNameLocation = location.state;
    var cityNameLocation = location.city;


    fetch('/locationTracker', {
      method: 'POST', 
      headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({
    locaionValues,
    countryNameLocation,
    stateNameLocation,
    cityNameLocation,
    })
  })
}
});

你可以展示你的前端HTML代码,以及后端想要如何处理代码,这将非常有帮助。另外,jQuery有
$.getJSON()
,这是上述方法的更好替代方法。如果您提供缺少的详细信息,我们很乐意为您提供帮助。令人惊叹的!国家:州:城市:是我的前端代码。没什么特别的,只是想把它隐藏起来,不显示在屏幕上,这样我就可以抓取这些数据。为什么不干脆做
$(“#country”).text()
所有人都可以从span tag获取数据?@Gianluca Yea,Swati的建议行得通。你能在这个问题上添加你的HTML和后端吗?我真的不明白,对不起。我刚刚更新了html回到问题中。。。
$(“#country”).text()会做什么?非常感谢!工作great@Gianluca很高兴我能帮忙。希望我的解释清楚。请随时提出更多问题。谢谢你激励我并提出这个问题!谢谢你添加这个。好的。
app.post('/locationTracker', (req, res) => {

var country = req.body.countryNameLocation
var state = req.body.stateNameLocation
var city = req.body.cityNameLocation
console.log("country is " + country)
console.log("state is " + state)
console.log("city is " + city)