2012-08-10 13 views
2

方案如何用javascript更新我的内容异步?

我正在写一个Web应用程序,MVC在我的情况,我需要从一个GET请求的响应更新特定容器,有时我要过滤的元素,并找到一个元素对放置在原始容器中的响应。

我该怎么办?

+1

你知道,有['.load()'](http://api.jquery.com/load/) – Alexander 2012-08-10 13:55:43

+1

您同时发布了一个问题和完整的fletched答案吗?它是否打算成为一个社区wiki? – Nope 2012-08-10 13:57:25

+1

的确,François,SO可以选择“回答你自己的问题”问答风格。那是我打算做的。 – Esteban 2012-08-10 14:14:44

回答

3

我是建立一个Web应用程序,当我需要更新部分我的内容异步

于是我想出了一个功能,这可能会适合您的需求了。在结果onSuccessonErroronComplete,并且可以过滤()和find()以及指定容器放置:

基本上,它会执行一个GET请求的URL提供的,它有标准的jQuery回调回应成。

假设你有这样的网页上:

<div id="myContentWrapper"> 
    <div class="myContent"> 
     <h1>This is the content I want to update.</h1> 
    </div> 
</div> 

和请求的响应返回此:

<html> 
    <!-- some html --> 
    <div id="filterId"> 
     <div class="findClass"> 
      <h1>This is the content I want to inject!</h1> 
     </div> 
    </div> 
    <!-- some more html --> 
</html> 

现在你可以更新布线功能myButton点击事件:

$("#myButton").click(function() { 
    loadContent("/Controller/Action", //url 
    "#filterId", ".findClass", //filter & find 
    "div#myContentWrapper div.myContent", //container to update 
    function() { //success callback 
     alert('Success!'); 
    }, function() { //error callback 
     alert('Error :('); 
    }, function() { //complete callback 
     alert('Complete'); 
    }); 
}); 

很容易的,现在该函数将做的工作的休息你:

function loadContent(url, filter, find, container, 
        onSuccess, onError, onComplete) { 
    var htmlResult; 
    $.ajax({ 
     url: url, 
     type: "GET", 
     success: function (data) { 
      htmlResult = data; 
      if (onSuccess && typeof onSuccess == "function") { 
       onSuccess.call(this); 
      } 
     }, 
     error: function() { 
      htmlResult = "<h1>An error occurred!</h1>"; 
      if (onError && typeof onError == "function") { 
       onError.call(this); 
      } 
     }, 
     complete: function() { 
      if (filter != null) { 
       if (find != null) { 
        $(container).html(
         $(htmlResult).filter(filter).find(find).html()); 
       } else { 
        $(container).html($(htmlResult).find(find).html()); 
       } 
      } else { 
       $(container).html(htmlResult); 
      } 
      if (onComplete && typeof onComplete == "function") { 
       onComplete.call(this); 
      }}});} 

也许你不希望过滤或查找响应的东西,所以你可以这样做:

loadContent("/Controller/Action", null, null, 
"div#myContentWrapper div.myContent", 
function() { 
    alert('Success!'); 
}, function() { 
    alert('Error :('); 
}, function() { 
    alert('Complete'); 
    }); 

或者,也许你并不需要任何回调:

//This is the basic function call, these parameters are required 
loadContent("/Controller/Action", null, null, 
    "div#myContentWrapper div.myContent", 
    null, null, null); 

现在你可以轻松地更新任何想要异步的内容,随时根据需要调整它,也可以使用请求类型参数,以便GET或POST,甚至可以添加图像容器这样你可以在你输入函数时显示它,并将它隐藏在$ .ajax的完整回调中。