我正在开发一个wordpress插件,其中我使用ajax调用提交表单数据,它工作正常,然后突然出现控制台错误,说ajaxurl(传递给ajax帖子的url)没有定义?我的jQuery函数:
$(".button").click(function() {
$(".error").hide();
var name = $(":input.name").val();
if (name == "") {
$("label#nameErr").show();
$(":input.name").focus();
return false;
}
var email = $(":input.email").val();
if (email == "") {
$("label#emailErr").show();
$(":input.email").focus();
return false;
}
var phone = $(":input.phone").val();
if ((phone == "") || (isNaN(phone))) {
$("label#phoneErr").show();
$(":input.phone").focus();
return false;
}
var info = \'name:\' + name + \'&email:\' + email + \'&phone:\' + phone;
var ajaxurl = \'<?php echo admin_url("admin-ajax.php"); ?>\';
alert(info);
jQuery.ajax({
type:"post",
dataType:"json",
url: ajaxurl,
data: {action: \'submit_data\', info: info},
success: function(response) {
if (response.type == "success") {
alert("success");
}
else {
alert("fail");
}
}
});
return false;
});
var ajaxurl=“”;line是我刚刚在web上找到的一个解决方案,但现在我的错误是403禁止。
SO网友:kai lange
请看这里:
http://codex.wordpress.org/Function_Reference/wp_localize_script
First add Data in your php file
// Register the script first.
wp_register_script( \'some_handle\', \'path/to/myscript.js\' );
// Now we can localize the script with our data.
$translation_array = array( \'some_string\' => __( \'Some string to translate\' ), \'a_value\' => \'10\' );
wp_localize_script( \'some_handle\', \'object_name\', $translation_array );
// The script can be enqueued now or later.
wp_enqueue_script( \'some_handle\' );
?>
After that you can use the data in js
alert(object_name.some_string);
// alerts \'Some string to translate\'