我在WordPress编辑帖子管理页面上有一个高级自定义字段,需要一些验证。这个验证是通过ajax完成的(我很确定,虽然acf和WordPress与这个问题无关)。
不幸的是,我在控制台中得到以下错误:Uncaught Not a valid flickr.com url
(第16行)用于以下代码:
jQuery(document).ready(function($) {
var initialVal = $('#acf-field_560aabcf8dbef').val();
$('#acf-field_560aabcf8dbef').on('paste', function(e) {
var pasteData = e.originalEvent.clipboardData.getData('text');
if (initialVal !== pasteData) {
try {
$.get(ajaxurl,
{
'action': 'ai_check_url_id',
'idOrUrl': pasteData
},
function(response) {
response = $.parseJSON(response);
if (response.error) {
throw response.error.msg;
}
console.log(response);
}
);
} catch (e) {
console.error(e);
}
};
});
});
php函数
<?php
function ajaxIdOrUrl()
{
try {
echo $this->idOrUrl($_GET['idOrUrl']);
} catch (Exception $e) {
echo json_encode([
'error' => [
'msg' => $e->getMessage(),
'code' => $e->getCode(),
],
]);
}
wp_die();
}
的作用是:
-
ajaxurl
在 页面上定义 - 在粘贴事件中检查值是否已更改
- 如果有,发出
get
请求并沿着 发送更改的数据。 - 答案是一个ID或一个错误数组
谁能指出我在正确的方向,为什么这显示为未捕获(代码工作良好时没有错误)?
感谢Matt Gibson的输入和这个答案。我已经重新设计了我的jQuery:
jQuery(document).ready(function($) {
var initialVal = $('#acf-field_560aabcf8dbef').val();
$('#acf-field_560aabcf8dbef').on('paste', function(e) {
var pasteData = e.originalEvent.clipboardData.getData('text');
if (initialVal !== pasteData) {
$.get(
ajaxurl,
{
'action': 'ai_check_url_id',
'idOrUrl': idOrUrl
}
)
.then(function(response) {
response = $.parseJSON(response);
if (response.error) {
return $.Deferred().reject(response.error)
} else {
return response;
}
})
.done(function(response) {
console.log(response);
// more sucess handling
})
.fail(function(err) {
console.error(err.msg);
// more error handling
});
};
});
});