填充一个HTML元素或jQuery的AJAX调用后创建一个选择更好的方式或可重复使用的code创建一个、或可、重复使用、元素

2023-09-11 22:34:48 作者:半岛湾季风

我觉得自己做的两件事情倒是常常用JS,目前使用jQuery:

I find myself doing 2 things quite often in JS, at the moment using jQuery:

首先是一个HTML元素的填充,这可能是这样的:

The first is the populating of an HTML element, which might look like:

$.get('http://www.example.com/get_result.php', { id: 1 }, function (data) {
    $('#elementId').html(data);
});

二是填充了JSON结果的select元素,如:

The second is populating a select element with a JSON result, such as:

$.getJSON('http://www.example.com/get_result.php', { id: 1 }, function(data) {
      $.each(data, function(value, name) {
          $('#selectField').append('<option value="' + value + '">' + name + '</option>');
      }
)};

我正在寻找的是无论是在做其中任一或延期(无论是库或code一大块)jQuery的,会做这些更好的东西,而无需重新创建code所有时间。或者是有一些已经在jQuery中,使这个更快?

What I'm looking for is either a better what of doing either of these or an extension (either library or a chunk of code) to jQuery that will do these without having to recreate the code all the time. Or is there already something in jQuery that makes this faster?

编辑:作为提到的Kevin戈斯基,填充HTML元素可以做的:

As mentioned by Kevin Gorski, populating the HTML element could be done as:

$('#elementId').load('http://www.example.com/get_result.php', { id: 1 });

这是完美的。尽管如此,如果你想做一个帖子,这是行不通的。然后做Collin艾伦的方法更好。

This is perfect. Although, if you wanted to do a POST, it wouldn't work. Then doing Collin Allen's method is better.

推荐答案

下面是一个简单的jQuery插件,我写了,使你的第一个例子更多的可重复使用的:

Here's a quick jQuery plugin I wrote that makes your first example more re-usable:

(function ($) {
    $.fn.populateWith = function(sUrl, oData, fCallback) {
        if (!oData) oData = false;
        if (!fCallback) fCallback = false;
        $(this).load(sUrl, oData, fCallback);
    };
})(jQuery);

您针对一个&LT;选择&GT; 元素(或一组元素,这取决于你的jQuery选择),只是在给定的结果,从像这样一个后台加载:

You target a <select> element (or group of elements, depending on your jQuery selector) and simply load in a given result from a backend like so:

$("#firstSelect").populateWith("backend.html");

或者,用一个回调,被炒鱿鱼负载完成后:

Or, with a callback that gets fired after the load is done:

$("#secondSelect").populateWith("backend.html", false, function() {
    alert('Callback fired!');
});

或者,有回调传递的数据:

Or, with callback and passed data:

$("#thirdSelect").populateWith("backend.html", {id: 1}, function() {
    alert('Callback fired with data!');
});

您也可以用一个数据对象,并没有回调调用它,但你的想法!基本上,这个小插件可以让你担心你想要的选项,并要将他们,而不在客户端的细节摆弄。从服务器端输出预计将纯HTML,但它可以很容易地适应以处理任何preferred格式。

You can also call it with a data object and no callback, but you get the idea! Basically, this little plugin lets you worry about what options you want and where you want them, without fiddling with the details on the client-side. Output from the server side is expected to be plain HTML, but it could be easily adapted to handle any preferred format.

希望这有助于!