Ajax Javascript函数在按钮上执行PHP代码

时间:2014-03-08 07:16:23

标签: javascript php jquery ajax

我正在运行以下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>';

它会触发PHP脚本。脚本工作,复制功能被触发。但是,我没有从Javascript函数获得任何反馈。你可以看到我实现了对console.log的回调。它声明:

Uncaught ReferenceError: do_delete is not defined options-general.php?page=upCustomBadges:177    onclick

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

首先仅在成功的ajax响应时显示结果

  //if success on ajax response
  echo 'if (xhReq.readyState==4 && xhReq.status==200){'; 
  echo    'document.getElementsByID("results").innerHTML=xhReq.responseText';  
  echo '}';

其次,callback未在任何地方定义。

答案 1 :(得分:0)

我现在采取了解决方法。像微风一样工作,即使它不那么漂亮。但现在已经足够好了:

<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>