如何将jquery的ajax响应数据传递给外部函数? [英] How to pass the jquery's ajax response data to outer function?
问题描述
Am从ajax调用获取数据并将数据附加到表中.我正在从数据中获取标题和网址.现在,当我单击table的url数据时,我需要使用单击的url数据调用外部javascript函数.
Am getting data from ajax call and appending the data to table. Am getting title and url from the data. Now when i click on the url data of table , i need to call a outer javascript function with the clicked url data.
<script>
jquery(document).ready(function(){
jquery(#button).click(function{
showData();
});
});
function showData(){
var total = "";
var final = "";
jquery.ajax({
url : "AJAX_POST_URL",
type: "POST",
data : input,
dataType: "json",
success: function(jsondata)
{
//data - response from server
var document= jsondata.data.results; //am getting array of objects
for(int i=0; i<document.length; i++){
var tr = "<tr>";
var td = "<td>" + "Title : " +
document[i].title + "Url :" + "<a href=''>" + document[i].url + </a> + "</td></tr>";
final = tr + td;
total= total + final ;
}
$("#docTable").append(total) ;
},
error: function (jqXHR, textStatus, errorThrown)
{
alert("error");
}
});
}
</script>
<script>
function download(){
//inside this function i need to get the value of document[i].url
}
</script>
推荐答案
您确实应该对程序进行更好的结构设计,并且如果可以将完整的示例放在jsfiddle.net上,将会更加容易.
You really should structure your program quite a bit better, and it would be easier if you could put your complete example up on jsfiddle.net.
但是,当前代码中的快速解决方案可能是使文档"成为全局变量.请注意,文档已经是BOM(浏览器对象模型)中的全局变量,因此请使用诸如"docs"之类的名称.
But a quick solution in your current code may be to make "document" a global variable. Beware that document already is a global variable in the BOM (Browser Object Model), so use something else like say "docs".
<script>
// Global variable
var docs;
jquery(document).ready(function(){
jquery(#button).click(function{
showData();
});
});
function showData(){
var total = "";
var final = "";
jquery.ajax({
url : "AJAX_POST_URL",
type: "POST",
data : input,
dataType: "json",
success: function(jsondata)
{
//data - response from server
docs = jsondata.data.results; //am getting array of objects
for(int i=0; i<document.length; i++) {
var tr = "<tr>";
var td = "<td>" + "Title : " +
docs[i].title + "Url :" + "<a href=''>" + docs[i].url + </a> + "</td></tr>";
final = tr + td;
total = total + final;
}
$("#docTable").append(total) ;
},
error: function (jqXHR, textStatus, errorThrown)
{
alert("error");
}
});
}
</script>
<script>
function download(){
//inside this function i need to get the value of document[i].url
// You have access to docs through the global variable
for(var i=0;i < docs.length;i++) {
console.log(docs[i].url)
}
}
</script>
这篇关于如何将jquery的ajax响应数据传递给外部函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!