I've been having a little problem getting the .html()
function in jQuery to work.
Basically, the page gets a bit of HTML via a PHP file using the jQuery post()
function, and then it has to insert it into the document. It gets the data from the PHP file fine, it just won't insert it into the document. The snippet of JavaScript code is below.
function lookup(inputString,location) {
if(inputString.length == 0) {
// Hide the suggestion box.
var suggestions = '#suggestions'+location;
$(suggestions).hide();
}
else {
$.post(
"boatnames.php",
{queryString: ""+inputString+"", number: ""+location+""},
function(data){
if(data.length >0) {
var suggestions = '#suggestions'+location;
$(suggestions).show();
var autosuggestions = '#autoSuggestionsList'+location;
$(autosuggestions).html(data);
}
});
}
}
function fill(thisValue,loca开发者_如何学运维tion) {
var textfield = "#BoatName"+location;
$(textfield).val(thisValue);
var suggestions = '#suggestions'+location;
$(suggestions).hide();
}
I am using jQuery 1.6, jQuery UI 1.8.16 and the latest version of jQuery validate. It works on another page, so most likely something I have messed up, but I cannot see it! All scripts are in the <head></head>
and the part I want to add the HTML to does exist.
If I remember correctly, the returned data
variable is an object and the actual HTML your page is returning is in the responseText
property.
You can try this:
$(autosuggestions).html(data.responseText);
When I have this type of problem, the cause is usually either:
- The selector is wrong, i.e., the variable autosuggestions does not hold the value of an actual element ID. (In my case, I've usually made a typo in somewhere.)
- The returned data is not valid HTML.
So, verify that:
- $(autosuggestions).length !== 0.
- typeof data is "string" and that string actually contains HTML.
jQuery has a function specifically designed for plopping HTML from the server into an element.
var autosuggestions = '#autoSuggestionsList'+location;
var params = {queryString: ""+inputString+"", number: ""+location+""};
$(autosuggestions).load("boatnames.php", params, function(){
var suggestions = '#suggestions'+location;
$(suggestions).show();
});
精彩评论