[英]Ajax Javascript Function to execute PHP Code on Button Press
I'm running the following Javascript function (from within a PHP script hence the echo): 我正在运行以下Javascript函数(从PHP脚本内运行,因此产生回声):
echo'<script type="text/javascript">';
echo'//Execute PHP Copy Script';
echo'function do_copy(){';
echo'var xhReq = new XMLHttpRequest();';
echo'var request = "../wp-content/plugins/upCustomBadges/copy.php" // prepare a request to script';
echo'xhReq.open("GET", request, false); // send a request';
echo'xhReq.send(null);';
echo'document.getElementsByID("results").innerHTML=xhReq.responseText /// display results';
echo'console.log(callback.toString());';
echo'}';
echo'<p><input type="button" value="Copy Badges" name="copy_badges" onclick="do_copy()" class="button-primary"></p>';
echo'<div id="results">Results';
echo'</div>';
It triggers a PHP script. 它触发一个PHP脚本。 The script works and the copy function gets triggered.
该脚本有效,并且复制功能被触发。 However, I don't get any feedback from the Javascript function.
但是,我没有从Javascript函数获得任何反馈。 I implemented a callback to console.log as you can see.
如您所见,我实现了console.log的回调。 It states:
它指出:
Uncaught ReferenceError: do_delete is not defined options-general.php?page=upCustomBadges:177 onclick
Any help would be appreciated! 任何帮助,将不胜感激!
First display your result only when your scuccessful ajax response 仅在您的ajax成功响应时才显示结果
//if success on ajax response
echo 'if (xhReq.readyState==4 && xhReq.status==200){';
echo 'document.getElementsByID("results").innerHTML=xhReq.responseText';
echo '}';
Second your callback
is not defined any where. 其次,您的
callback
没有在任何地方定义。
I went with a workaround now. 我现在有一个解决方法。 Works like a breeze, even tho it's not as pretty.
像微风一样工作,甚至不那么漂亮。 But good enough for now:
但目前已经足够好了:
<script type="text/javascript">
function do_copy(){
var xhReq = new XMLHttpRequest();
var request = "../wp-content/plugins/upCustomBadges/copy.php";
xhReq.open("GET", request, false);
xhReq.send(null);
var serverResponse = xhReq.responseText;
alert(serverResponse);
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.