2015-04-22 132 views
1

我在爲wordpress寫一個插件。該插件有一個包含按鈕和文本框的小部件。 該按鈕有onclick事件。 當發生此事件時,我需要將文本框數據發佈到php文件,使用ajax ajax代碼不會返回錯誤,但php不會獲取數據。wordpress插件中的ajax錯誤

這裏是我的JS文件

function F() 
    { 
     var x=document.getElementById('last').value; 


     jQuery.ajax({ 
      type: "POST", 
      url: 'http://localhost/wordpress/wp-content/plugins/Hovo/Scripts/vote.php',   
      data: x, 
      success: function() { 
       alert('Sends successfully'); 
      }, 
      error: function(jqXHR, textStatus, errorThrown) { 
      alert(errorThrown); 
      } 
     }); 
    } 

這裏是我的PHP文件

<?php 
    if(isset($_POST["anun"])) 
    { 
     echo $_POST['anun']; 
    } 
    else 
    { 
     echo "error"; 
    } 
?> 

請幫忙解決這個問題

+0

你確定本地主機?你在電腦上用於服務器端的東西?例如我usq麻,我的網站localhost:8888,或localhost:3000 – Legendary

回答

0

在你的PHP $_POST期待一個鍵/值對,你是在你的ajax中只發送一個值。 'anun'將是關鍵,無論存儲在x是值。

既然你不發送密鑰「anun」到$_POST不能返回存儲在x因爲你if條件失敗的價值。

您應該能夠通過稍微改變你的Ajax調用來糾正這一點,

function F() { 

    var x = document.getElementById('last').value; 

    jQuery.ajax({ 
     type: "POST", 
     url: 'http://localhost/wordpress/wp-content/plugins/Hovo/Scripts/vote.php',   
     data: { anun: x }, 
     success: function() { 
      alert('Sends successfully'); 
     }, 
     error: function(jqXHR, textStatus, errorThrown) { 
     alert(errorThrown); 
     } 
    }); 
} 

爲了確保你能獲得的x正確的值,請嘗試使用console.log(x);只是你的AJAX調用之前,檢查瀏覽器控制檯看看它的回報。

如果它不返回正確的值或者幹​​脆沒有返回,請嘗試更改:

var x = document.getElementById('last').value; 

要簡單地說:

x = jQuery('#last').val();