When an AJAX call returns html, is it possible to use jQuery 开发者_StackOverflowto alter the contents of the response string? If so, how does one go about doing that?
EDIT:
This question is directed at editing the response before writing it to the page
Well that depends on how you request the data. If you have $.ajax etc, then you can do the necessary modifications in the success handler. I assume since you don't understand jQuery very well, that you are using $.load() to load the data, in which case it's easiest to replace it with
$.get('/somecode.php', function(data) {
data = $(data);
// Find and remove all anchor tags for example
data.find('a').remove();
$('#target-id').append(data);
});
Or if you don't want to create a jQuery object, you can easily do something like
$.get('/somecode.php', function(data) {
// Replace all strings "foo" with "bar" for example
data = data.replace('foo', 'bar');
// Manually append it to DOM or do whatever you want with it
$('#target-id').append(data);
});
If you're using jquery 1.5+ you can use ajax datafilter.
dataFilter callback option is invoked immediately upon successful receipt of response data. > It receives the returned data and the value of dataType, and must return the (possibly > altered) data to pass on to success.
Sample Code :
$.ajaxSetup({
dataFilter: function (response, type) {
response = response.replace(/username/g, 'Sina Salek');
return response;
}
});
https://api.jquery.com/jquery.ajax/
in callback function, which looks something like
function(response){
response = //edit response here
$("#content").html(response);
}
You can edit the content of the returned data with jQuery by transforming the data itself in a jquery object.
$.get(file.html, function(data){
var $obj = $('<div>').html(data); //explaination of this below
$obj.find("span").remove(); //just an example, this removes all the SPANs
$("#destination").html($obj.first('div').html());
});
Please note that you need to wrap the returned data in a DIV, before editing it, because if your returned data has not a valid root node in the HTML structure, the jQuery object will not be able to perform modification with the find and other functions.
For this reason it's a good practice to wrap the returned data, modify it, and then unwrap it before the insertion in the destination html node.
Edited on maxedison's accuracy advice:
You can directly manipulate the return string as genesis pointed out (no need for JQuery to do that), or you can recreate a new output by parsing the html, using an helper library like jParse:
http://jparse.kylerush.net/demo
Primitive javascript
core: Object.defineProperty(this, 'responseText', { value: JSON.stringify(data), writable: false });
The method of using object assignment will be invalid, this.responseText = {...};
<button>send</button>
<p>hello</p>
<script>
const nativeOpen = XMLHttpRequest.prototype.open;
const nativeSend = XMLHttpRequest.prototype.send;
const proxiedOpen = function () {
// Mount the URL that needs to be intercepted to the `XMLHttpRequest` object.
if (arguments[1].includes('jsonplaceholder.typicode.com/todos/1')) this._url = arguments[1];
nativeOpen.apply(this, arguments);
};
const proxiedSend = async function () {
if (this._url) {
// Make other requests, it can also be a fixed value.
const data = await fetch('https://jsonplaceholder.typicode.com/todos/5').then(res => res.json());
// The data of `todos/1` is rewritten as `todos/5`
Object.defineProperty(this, 'responseText', { value: JSON.stringify(data), writable: false });
}
nativeSend.apply(this, arguments);
};
// Override native methods
XMLHttpRequest.prototype.open = proxiedOpen;
XMLHttpRequest.prototype.send = proxiedSend;
document.querySelector('button').addEventListener('click', () => {
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.querySelector('p').textContent = this.responseText;
}
};
xhttp.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);
xhttp.send();
});
</script>
No. jQuery will only operate on DOM elements. So until those are created from the string, all you have is... a string.
Can I ask why you're concerned about doing this? If it's a performance issue (i.e. you're creating a ton of DOM elements with the AJAX response, and then editing a lot of them with jQuery), then chances are that your PHP script should be modified to return a more desirable response. If the problem is that you don't want users to see the response until the DOM modifications have been made by jQuery, then just stick it all in a hidden div (display:none) until the modifications are complete.
Edit - 1 exception jQuery has a $.trim() function which will remove whitespace from the beginning and end of a string. Not sure if there are any others.
精彩评论