我在这里遇到了一些javascript。我需要将动态变量/变量传递给外部函数。这是生成PHP网页URL的函数,我最终尝试将一些数据发布到(不是完整函数,只有重要部分):
var id = "";
var name = "";
var url = "";
function initialize () {
downloadUrl("phpsqlajax_genxml1.php", function (data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var id = markers[i].getAttribute("id");
var name = markers[i].getAttribute("name");
var description1 = markers[i].getAttribute("description");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var url = "markerpages.php?name=" + name + "&id=" + id;
var html = "<b>" + name + "</b> <br/>" + description1;
var contentString = '<div id="content">' +
'<div id="siteNotice">' +
'</div>' +
'<h1 id="firstHeading" class="firstHeading">' + name + '</h1>' +
'<div id="bodyContent">' +
'<p>' + description1 + '</p>' +
'<p><a href="'+ url +'" onclick="postData(url)">Link to PHP web page</a>' +
'</p>' +
'</div>' +
'</div>';`
我有&#39; url&#39;变量全局定义,然后我的postData函数看起来像这样,并且在initialize函数之外:
function postData(arg) {
alert("Url: "+url+"Name: "+name+"ID: "+id);
$(document).ready(function () {
var href = $('.postData').attr('href');
var id = markers[i].getAttribute("id");
var name = markers[i].getAttribute("name");
var url = "markerpages.php?name=" + name + "&id=" + id;
window.location.href = href;
console.log("outside ajax is working");
console.log(url);
$.ajax({
type: "POST",
url: ' + url + ',
data: {
source1: "some text",
source2: "some text 2"},
success: function (data) {
console.log(data);
console.log(url);
console.log("inside ajax is working");
}
});
});
}
jquery正在触发onclick,但url以未定义的形式返回,所以我只需要引入根据存储在数据库中的标记名生成的url变量。我是初学者,所以这可能很简单。我环顾了论坛和文档,但几个小时都未能弄明白,哈哈。
真诚地感谢您的帮助!
答案 0 :(得分:0)
将变量声明在所有函数范围之外,如下所示:
//Declare the three variables globally
var url = "";
var name = "";
var id = "";
...
function initialize () {
...
//id and name are local to this function, if you want them to be global as well
//declare them outside the scope of all functions along with url variable
//Assign them suitable values
id = markers[i].getAttribute("id");
name = markers[i].getAttribute("name");
url = "markerpages.php?name=" + name + "&id=" + id;
...
}
function postData(arg) {
//Use all the variables here directly for example you could just try alerting them
alert("Url: "+url+"Name: "+name+"ID: "+id);
}
您的案例中的问题是“url”变量不全局。您分别在postData(arg)
和initialize()
函数中声明了url变量,因此该变量在这些函数的范围内是本地的。
此外,在postData(arg)
功能中,您可以执行此操作:
var id = markers[i].getAttribute("id");
var name = markers[i].getAttribute("name");
var url = "markerpages.php?name=" + name + "&id=" + id;
但是,markers
数组遍历initialize()
函数,而不是postData
函数。如果您想在此上下文中访问“id”和“name”变量。只需在所有函数范围之外声明它们一次,并在稍后的任何上下文中初始化或更新它们,就像我用'url'变量显示一样。