将参数传递给函数(ajax,javascript,jquery)

时间:2013-04-15 11:54:09

标签: javascript jquery

如何将x参数传递给函数startTable? 我想按作者过滤结果,并且已经坚持了几天......

$(document).ready(function () {
    var result;
    alert('ajax works');
    $.ajax({
        type: "GET",
        url: "xml.php",
        cache: true,
        dataType: "xml",
        success: function (xml) {

            function startTable(x) {
                $(xml).find("item").each(function (index) {
                    var author = $(this).find('author').text();
                    var title = $(this).find('title').text();
                    var rating = $(this).find('rating').text();
                    var review = $(this).find('review').text();
                    // Checks the condition
                    if (author == x) {
                        $('#input1').append('<tr><td>Title: <b>' + title + '</b></td><td>Rating: <b>' + rating + '</b></td></tr><tr><td colspan="2">' + review + '</td></tr>');
                    }
                });
            };

        }
    });
});

function startFilter() {
    var x = document.getElementById('inputFilter').value;
    // Passing parameter
    startTable(x);
};

任何想法? 提前谢谢。

2 个答案:

答案 0 :(得分:0)

您无法从外部拨打本地电话。您应该做的是过滤成功回调函数

中的响应数据
$.ajax({
    type: "GET",
    url: "xml.php",
    success: function (response) {
      render_and_filter(response);
    }
});

function render_and_filter(data){
 // ... append or update your data to document here ...
}

答案 1 :(得分:0)

我重新编写代码来调用ajax,然后使用它 - 全部由执行启动。这有点笨拙,但你可以继续工作。

function startTable(x, xml) {
    $(xml).find("item").each(function (index) {
        var xmlItem = $(this);
        if (xmlItem.find('author').text() == x) {
            var thisItem = {
                title: xmlItem.find('title').text(),
                rating: xmlItem.find('rating').text(),
                review: xmlItem.find('review').text()
            };
            $('#input1').append('<tr><td>Title: <b>' + thisItem.title + '</b></td><td>Rating: <b>' + thisItem.rating + '</b></td></tr><tr><td colspan="2">' + thisItem.review + '</td></tr>');
        }
    });
}

function getData(x) {
    var result;
    alert('ajax works');
    $.ajax({
        type: "GET",
        url: "xml.php",
        cache: true,
        dataType: "xml",
        success: function (xml) {
            startTable(x, xml);
        }
    });
}

function startFilter() {
    var x = document.getElementById('inputFilter').value;
    // Passing parameter
    getData(x);
}

//get started
startFilter();

现在它可能只是我,但你可能会在服务器上过滤你的结果(传递“x”值并只返回你需要的东西,但这取决于你。