How to use jQuery ajax to set the content of a div, then call JS from that div
I'm using JQuery to load the content of an MVC usercontroll:
function menuShowModal(a) {
$.ajax(
{
url: a.href,
success: function (result) {
$('#modalDialog').dialog('close');
var $dialog = $('<div id=\'modalDialog\'></div>')
.html(result)
.dialog({
autoOpen: true,
title: 'Basic Dialog',
modal: true
});
},
cache: false,
type: 'get'
});
return false;
}
The returned HTML looks like this:
<input type="text" id="navnet" value="test" />
<script type="text/javascript">
$(document).ready(
function () {
alert($("#navnet").val());
}
)
</script>
The problem is that the alert returns "undefined" and not "test" as it should, in other words the JS is executed before the html is inserted, how do I work around this?
-- solution from below post is a callback function, here 开发者_如何学编程is the working code --
function menuShowModal(a) {
$.ajax(
{
url: a.href,
success: function (result) {
onDialogBoxShown = null;
$('#modalDialog').dialog('close').remove();
var $dialog = $('<div id=\'modalDialog\'></div>')
.html(result)
.dialog({
autoOpen: true,
title: 'Basic Dialog',
modal: true
});
if (onDialogBoxShown != null) onDialogBoxShown();
},
cache: false,
type: 'get'
});
return false;
}
<input type="text" id="navnet" value="test" />
<script type="text/javascript">
var onDialogBoxShown = function () { alert($("#navnet").val()); }
</script>
The document has already been loaded (the snippet you insert is not a document), so your callback fires immediately. Try this:
<script type="text/javascript">
alert($("#navnet").val());
</script>
Alternatively define a function and call it explicitly after the html has been inserted:
<script type="text/javascript">
var mycallback = function() { alert($("#navnet").val()); }
</script>
...
.html(result);
if (typeof window.mycallback == 'function') mycallback();
If possible, better approach would be getting rid of the <script>
element and putting all your code in success callback.
I think the problem is that until you call dialog() the html just floats around in memory and is not appended to the DOM so you can't find elements in it by ID.
This should work:
$('#modalDialog').dialog('close');
var $dialog = $('<div id=\'modalDialog\'></div>').css('display','none');
$(document.body).append($dialog);
$dialog.html(result)
.dialog({
autoOpen: true,
title: 'Basic Dialog',
modal: true
});
精彩评论