Ajax xml源解析依赖于jQuery的点击操作

Ajax xml source parsing depend on click action with jQuery

本文关键字:操作 jQuery 依赖于 xml Ajax      更新时间:2023-09-26

我有一个AJAX xml解析:

$.ajax({
    type:"GET",
    url: "data/content_data.xml",
    dataType:"xml",
    success: function(xml) {

在单击某个按钮元素后,是否有任何更改源的选项?例如,我单击按钮_01并从url: "data/content_data_01.xml"加载脚本加载源,单击按钮_02从url: "data/content_data_02.xml"加载源。

设置一些按钮:

<input type="button" id="B01" value="Get nr. one" />
<input type="button" id="B02" value="Get nr. two"/>

做一些jQuery的东西:

$('button').on('click', function() { //attach click handler
    doAjax(this.id.replace('B','')).done(function(xml) { // remove B and do ajax
        //do something with xml in the deferred callback
    });
});
function doAjax(url_id) { //url_id value will be 01 or 02 and ....
    return $.ajax({
        type:"GET",
        url: "data/content_data_"+url_id+".xml", //is inserted here in the url
        dataType:"xml"
    });
}

当然。有很多方法可以做到这一点。基本上,你只需要为url值使用一个字符串变量,而不是一个文本字符串。你也许可以定义一个对象,用来查找这个中的值

var buttonIDtoURL = {
    "button_01": "data/content_data_01.xml",
    "button_02": "data/content_data_02.xml"
}
$(".button_class").click(function() {
    var urlToUse = buttonIDtoURL[$(this).id];
    $.ajax({
        type:"GET",
        url: urlToUse,
        dataType:"xml",
        success: function(xml) {
            // your success handler here
        }
    });
 });