2015-11-24 125 views
-1

我有一个使用AJAX get方法调用PHP脚本的Javascript。如果我从外部运行PHP脚本,它工作正常,并创建文件connections.txt。但随着JS它不工作尝试从Javascript运行本地PHP文件,本地都运行

$(document).on("click", "#target2", function(){ 
var arr = ["one","two","three"]; 
$.ajax({ 

       type: 'POST', 

       url: 'hello.php', 
       data: { name: "saurabh" }, 
       success : function(msg) { 

        // here is the code that will run on client side after running clear.php on server 

        // function below reloads current page 
        alert(msg); 

       } 

}); 

}); 

PHP脚本:

<?php 
    $fp = fopen('/Users/saurabh/Desktop/connections.txt', 'w'); 
    echo "Saving file"; 
    fwrite($fp, "hello"); 
    //echo $_POST['yourarray']); 
    fclose($fp); 
?> 
+2

你是什么意思“它不工作”?开发者控制台的网络选项卡中是否出现404或500错误? – rjdown

+0

你是否将你的点击绑定包装在一个就绪函数中:$(function(){...}); –

+0

不,我已测试点击,它工作正常。我面临的问题是使用POST方法。我得到405错误: [2015-11-26 00:15:36]错误不支持的方法'POST'。 localhost - - [26/Nov/2015:00:15:36 CET]“POST /hello.php HTTP/1.1”405 300 http:// localhost:8000/- > /hello.php –

回答

0
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
<script> 
$(document).ready(function(){ 
    $.ajax({ 
     type: 'POST', 
     url: 'hello.php', 
     data: { name: "saurabh" }, 
     success : function(msg) { 
      alert(msg); 
     } 
    }); 
}); 
</script> 

我只是跑了在我的本地,并能正常工作。你必须在onclick函数上犯一些错误。做这样的事情...

$(document).ready(function(){ 
    $("#someButton").click(function(){ 
     $.ajax({ 
      type: 'POST', 
      url: 'hello.php', 
      data: { name: "saurabh" }, 
      success : function(msg) { 
       alert(msg); 
      } 
     }); 
    }); 
}); 
+0

不,有点击按钮没有问题。我面临的问题是Post功能。我得到错误405 300: [2015-11-26 00:15:36]错误不支持的方法'POST'。 localhost - - [26/Nov/2015:00:15:36 CET]“POST /hello.php HTTP/1.1”405 300 http:// localhost:8000/- > /hello.php –