2015-11-24 121 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 –