我有一个ASP.NET MVC3应用程序,我的任务是将一些HTML代码(某种形式)和Javascript代码(主要是插入表单的jQuery验证)插入到网页的DOM中 - HTML和Javascript代码都是通过Ajax调用返回的:
var id = jQuery(this).attr("data-id");
var querystring = "id=" + id;
jQuery.ajax({
type: "GET",
url: "Home/GetEditViewHTMLById",
data: querystring,
dataType: "html"
}).done(function (msg_html) {
jQuery.ajax({
type: "GET",
url: "Home/GetEditViewJavascriptById",
data: querystring,
dataType: "script"
}).done(function (msg_javascript) {
jQuery("#content").html(msg_html); // inserting the HTML
var script = document.createElement("script");
script.type = "text/javascript";
script.text = msg_javascript;
document.body.appendChild(script); // inserting the Javascript - doesn't work
Edit(); // <- this function would be in the inserted Javascript code
});
});
“msg_javascript”变量包含Javascript代码,如果我调用alert,我可以看到Ajax调用的结果:
function Edit(){
jQuery("#plugin").validate( { errorElement: 'div' } );
jQuery("#sum1").rules("add", { required: true, messages: { required: "!" } });
jQuery.validator.addMethod("regex_sum1",
function (value, element, regexp) {
var check = false;
var re = new RegExp(regexp);
return re.test(value);
},
"Wrong number format!");
jQuery("#sum1").rules("add", { regex_sum1: "^[1-9][0-9]*$" });
jQuery("#sum2").rules("add", { required: true, messages: { required: "!" } });
jQuery.validator.addMethod("regex_sum2",
function (value, element, regexp) {
var check = false;
var re = new RegExp(regexp);
return re.test(value);
},
"Wrong number format!");
jQuery("#email").rules("add", { required: true, messages: { required: "!" } });
jQuery.validator.addMethod("regex_email",
function (value, element, regexp) {
var check = false;
var re = new RegExp(regexp);
return re.test(value);
},
"Wrong e-mail format!");
jQuery("#email").rules("add", { regex_email: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$" });
jQuery('input').blur(function(){
if(!jQuery(this).valid()){
return false;
}
});
function calculate(){
return (Number(jQuery('#sum1').val())*(Number(jQuery('#sum2').val())+0.5));
}
function getFields(){
return ["sum1","sum2"];
}
function validateRange(value){
return 1000 <= value && value <= 10000;
}}
如果我从服务器返回以下功能:
function Edit(){
alert("okay");
}
答案 0 :(得分:1)
Javascript不会在返回的变量中运行,您必须执行它:
eval(msg_javascript);