Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

loading page framents with Jquery AJAX

I would like to use $.ajax() to request a page, but load only fragments of that page. I know you can specify what page fragments you want with .load() but I was wondering if this is possible with $.ajax?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For those of you who are wondering, stoplion is referring to this feature: Loading Page Fragments (scroll down on the page):

The .load() method, unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.

Since $.get() doesn't appear to support it, I assume that $.ajax wouldn't either. A simple way to implement this would be the following:

$.ajax({
   url: 'http://example.com/page.html',
   data: {},
   success: function (data) {
      $("#el").html($(data).find("#selector"));
   },
   dataType: 'html'
});

This would be the equivalent of

$("#el").load('http://example.com/page.html #selector');

However, note that the special syntax (' #selector') means that scripts present in the loaded HTML will not be executed. See Script Execution in the .load() docs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...