Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to select script tags from a jQuery ajax get response

Tags:

jquery

I'm on page A. A link is clicked, and I'm loading in the DOM via jQuery get from page B. Inside page B's DOM are multiple dynamically-generated script tags with the class "dataScript" along with a bunch of other script tags that I don't want anything to do with.

The only thing I want from that DOM are the .dataScript tags, which I then want to insert into a div with an ID of "scriptOutput" into the DOM of page A. This won't work if the element with the class of "dataScript" is a script tag. Only if it's some other tag, such as a "div" tag. Here's an example of what I'm trying to do:

Page A:

<html>
<head>
<title>Page A</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function() {
 $("#ajaxJsLink").click(function() {
  $.get("pageB.html", function(data) {
   var scriptElements = $(data).find(".dataScript").contents();
   console.log(scriptElements);
   $(scriptElements).each(function(index) {
    $("#scriptOutput").append($(this).html());
   });
  });
  return false;
 });
 $("#ajaxDivsLink").click(function() {
  $.get("pageB.html", function(data) {
   var scriptElements = $(data).find(".dataDiv").contents();
   console.log(scriptElements);
   $(scriptElements).each(function(index) {
    $("#divOutput").append($(this).html());
   });
  });
  return false;
 });
});
</script>
</head>
<body>
<p>This is page A.</p>
<hr />
<p>
<a href="pageB.html" id="ajaxJsLink">Get JavaScript from Page B.</a><br />
<a href="pageB.html" id="ajaxDivsLink">Get Divs from Page B.</a>
</p>
<hr />
<div id="scriptOutput">
 <h2>Script Output</h2>
</div>
<div id="divOutput">
 <h2>Div Output</h2>
</div>
</body>
</html>

Page B:

<html>
<head>
<title>Page B</title>
</head>
<body>
<p>This is page B.</p>
<div id="scripts">
 <script type="text/javascript" class="dataScript">
  function someFunction() {
   alert("I am");
  }
 </script>
 <script type="text/javascript" class="dataScript">
  function anotherFunction() {
   alert("Javascript");
  }
 </script>
</div>
<div id="divs">
 <div class="dataDiv">
  <div>
   function someFunction() {
    alert("I am");
   }
  </div>
 </div>
 <div class="dataDiv">
  <div>
   function anotherFunction() {
    alert("Html");
   }
  </div>
 </div>
</div>
</body>
</html>

I've tried appending .contents(), .html(), and .text() for the .dataScript content, but nothing seems to work. Thanks for your consideration in looking at/answering my questions. I appreciate your help!


UPDATE:

In case anyone else is trying to do this, here is the less-than-elegant but fully-functional solution I ended up with:

Output javascript as regular text (no script tags) inside one div (with an ID and set to display:none) on Page B. Then on Page A, do the following inside the callback function of the get request:

var docHead = document.getElementsByTagName("head")[0]; //head of Page A
var newScript = document.createElement("script");
newScript.setAttribute("type","text/javascript");
newScript.innerHTML = jQuery(data).find("#divWithPlainTextJs").text(); //insert plain text JS into script element
docHead.appendChild(newScript); //append script element to head of Page A
jQuery("#divWithPlainTextJs").remove(); //remove the plain text div and JS from the DOM

Thanks to Emmett for reminding me of the document.createElement method.

like image 666
esvendsen Avatar asked Dec 13 '10 15:12

esvendsen


People also ask

What is the response in Ajax?

Response is the object passed as the first argument of all Ajax requests callbacks. This is a wrapper around the native xmlHttpRequest object. It normalizes cross-browser issues while adding support for JSON via the responseJSON and headerJSON properties.

What is get request in Ajax?

get() method requests data from the server with an HTTP GET request. Syntax: $. get(URL,callback); The required URL parameter specifies the URL you wish to request.

What is the use of Ajax () method?

The ajax() method is used to perform an AJAX (asynchronous HTTP) request. All jQuery AJAX methods use the ajax() method. This method is mostly used for requests where the other methods cannot be used.


1 Answers

jQuery doesn't actually append <script> elements to the DOM. Instead, it just evals the contents of the script. Since it isn't in the DOM, $(data).find(".dataScript") doesn't match anything.

If you really need the contents of the <script> tag, you could try using a regular expression to parse the ajax response.

Check out Karl Swedberg's comment for more info:

All of jQuery's insertion methods use a domManip function internally to clean/process elements before and after they are inserted into the DOM. One of the things the domManip function does is pull out any script elements about to be inserted and run them through an "evalScript routine" rather than inject them with the rest of the DOM fragment. It inserts the scripts separately, evaluates them, and then removes them from the DOM.

I believe that one of the reasons jQuery does this is to avoid "Permission Denied" errors that can occur in Internet Explorer when inserting scripts under certain circumstances. It also avoids repeatedly inserting/evaluating the same script (which could potentially cause problems) if it is within a containing element that you are inserting and then moving around the DOM.

like image 196
Emmett Avatar answered Nov 01 '22 11:11

Emmett