请容忍我,我已经和这个斗争好几天了。
我的jQuery (文档).ready函数中有一些jQuery代码,如下所示:
jQuery(document).ready(function($) {
jQuery.post(ajaxurl, data, function(response) {
alert(response);
});
});我有一个文本输入字段,我想要发送到我的Ajax函数(使用Wordpress API)
<input type="text" name="input" id=input onkeydown="if (event.keyCode == 13) {send_message(this.value);}">如果用户按下键,文本将发送到javascript 'send_message‘函数(下面)。
function send_message(value){
data[txt]=value;
jQuery.post(ajaxurl, data, function(response) {
alert(response);
});
}BAsically,我向我的数据对象添加了一个'txt‘键/值对,现在我希望将它提交给我的ajax函数。
“document”部分工作正常,但我无法让它接受已更改的数据对象。
正如您可能知道的,我没有很好地遵循jQuery代码背后的逻辑。
发布于 2015-09-01 00:02:43
function send_message(value){
if(!value){
alert('value is empty');
}
if(!data){
alert('data is empty');
}
data.txt=value;
jQuery.post(ajaxurl, data, function(response) {
alert(response);
});
}如果您检查您的控制台,您可能会得到txt是没有定义的,您错过了围绕在它们周围的“”。通常对已知的对象键使用.dot表示法,如果您相信良好的实践,则为动态键保存[]。
此外,您也没有提到您使用的是什么浏览器……我不能发誓这是当前的,但是firefox使用的是event.which而不是keycode...so:
onkeydown="var code= event.which || event.keyCode; if (code == 13) {send_message(this.value);}"编辑
此实例的解决方案。
您在钩子'enqueue_scripts‘上排队,它应该是'admin_enqueue_scripts’,并指定它需要jQuery。
add_action( 'admin_enqueue_scripts', 'load_chat_me_styles' ); //-->note changed hook!我还更新了js文件以支持控制台日志和php文件,以便进行更好的反馈。
Jsfile -保存为一个新的文件名,以排除缓存http://pastebin.com/NyqGqhG0
记录任何音符..。http://pastebin.com/N7LQg0Zi
发布于 2015-08-31 15:56:43
未初始化函数中的数据参数。如果使用chrome或firefox检查页面,可能会看到javascript错误。
基本上,jquery的post函数中的数据参数接受序列化的表单查询字符串或JSON字符串/对象。
另外,请检查api:http://api.jquery.com/jquery.post/
尝试以下修改的代码:
function send_message(value){
var data={txt:value};
jQuery.post(ajaxurl, data, function(response) {
alert(response);
});
}https://stackoverflow.com/questions/32315109
复制相似问题