JQuery.Ajax (), saving certain data in a variable

I am new to jQuery and I have the following problem.

My project said 2 pages, 1.JSP and 2.html. Now I want to select the selected data from 2.html and use it on 1.JSP. Now this was achieved very easily with .load , but I want the data to be present in the JavaScript variable and not put it on the page (div tags, etc.), so that I can work with this data (modify or add databases data).

I tried using .ajax and was able to write the following code:

  var value = (function () { var val = nulll; var filename = " 2.html"; $.ajax ({ 'async': false, 'global': false, 'url': filename, 'success' : function(data) { val = data; } }) return val; })() document.write(value) 

Where can I put the selector format (say div.id5) so that my variable has only the relevant data and not the complete file data?

+4
source share
3 answers
 function modify_data(data){ .... } $.ajax({ type: "POST", //POST OR GET url: "1.JSP", // URL TO SEND AJAX DATA TO data: "name=John&location=Boston", // DATA TO SEND success: function(data){ // CALLBACK FUNCTION modify_data(data);// sending data to another function to play with it $('body').html(data); } }); 

Here's how to send an Ajax request and print it on the body after changing the received data.

+1
source

Say you have 1.html and 2.html, and inside the body of 2.html you have this:

 <body> <h1 id="foo">hello</h1> </body> 

Then in your 1.html you will get the text inside H1 as follows:

 var filename = " 2.html"; $.ajax ({ 'async': false, 'global': false, 'url': filename, 'success' : function(data) { var html = $(data); html.each(function() { if(this.tagName && this.tagName == 'H1') { alert( $(this).html() ); } }) } }) 

This should trigger an annoying JS warning with a "hello" written inside it.

0
source

I assume that you are referring to the ability of the $ .load () function to receive a jquery selector along with a URL to filter the result. To say today you do it like this:

 $('div').load('2.html div.id5'); 

So you really want to be able to do the same with the $ .ajax () function. I believe the easiest way to do this is to use the jQuery.find () function inside your success event function (I omit the .ajax () call by simply typing the success event code):

 success: function (data) { val = $(data).find('div.id5').html(); // now you ony have that specific div contents } 

I saw several other errors in your javascript code that I think you need to fix (if you really use this code).

  // null is defined with 2 ls var val = nulll; // Is the space on purpose? var filename = " 2.html"; 
0
source

Source: https://habr.com/ru/post/1302113/


All Articles