我正在尝试使用一些我可以从在线收集的Ajax代码来记录我的用户位置。我正在尝试将其传递给后端代码,以便在其中将数据存储在数据库中进行分析。我以前从未使用过Ajax,并且不熟悉传递到后端的语法。
这是我的代码。
<div>Country: <span id="country"></span>
<div>State: <span id="state"></span>
<div>City: <span id="city"></span>
$.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);
}
});
我基本上需要传递$('#country').html(location.country_name); $('#state').html(location.state); $('#city').html(location.city);
给我的nodejs代码。我以前在js中使用过fetch,但不确定是否要在其中包含Ajax代码的语法。感谢帮助。
如果您有一些数据要使用AJAX发送到服务器,并且有类似HTML的内容,则可以很好地使用元素的textContent
or .text()
(使用jQuery)。这是您的操作方式。
// Sending data to the server...
var data = {
country: $("#country").text(),
state: $("#state").text(),
city: $("#city").text()
};
console.log("Data to be sent!");
console.log(data);
console.log("Serialised data!");
console.log($.param(data));
// Send data to end point and get JSON value.
$.getJSON("/endpoint?" + $.param(data), function (res) {
console.log(res);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Country: <span id="country">India</span>
<div>State: <span id="state">Tamil Nadu</span>
<div>City: <span id="city">Chennai</span>
在上面的示例中,HTML的内容将发送到服务器。检出控制台和网络以查看发送的内容。
这是来自Google Chrome浏览器的“网络”标签:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句