2015-03-25 36 views
0

好的,這是我的問題。Ajax的數據參數沒有送到服務器

我有一個HTML頁面,其中已初始化一個JavaScript變量。

<html> 
    <script> 
     MyVaribale = "Random Data"; 
    </script> 

    <!-- Then I include an external js file to handle the processes in this html file --> 

    <script type="text/javascript" language="javascript" src="/scripts/some_random_script.js"></script> 

</html> 

現在,在該腳本中。我用MyVaribale varible在Ajax請求有一個,像這樣:

$(document).ready(function() { 
    $.ajax(
     url : '/some/random/url', 
     data : { MyVariable : MyVaribale } 
     etc ... 
    ); 
}); 

所以,在頁面加載,即Ajax代碼,立即執行。

在上面指定的url中,我檢查了MyVaribale的存在,然後標記一個錯誤,如果它不存在,則爲必需值。

後端這樣的代碼(在Perl):

my $MyVariable = trim_param('MyVariable'); # trim_param() is a function that gets the passed data from ajax. 

if ($MyVariable) { # Test if it exists 
    # Display something 
} 
else { 
    # Flag an error, which is my problem 
} 

現在我相信,在HTML頁面,該變量總是被填充(是100%確定)。但我總是得到標誌錯誤,該值不存在於我的後端代碼(上面的URL)中。

這樣的問題,

是否阿賈克斯一些問題與document.ready,也許它執行變量已完成分配一個值之前?任何想法爲什麼發生這種情況因爲有時我的Ajax請求是成功的,有時不是

感謝

+0

你可以發佈你的後端代碼嗎? – 2015-03-25 07:18:22

+0

@HastaPasta編輯我的文章 – user2881063 2015-03-25 07:29:10

+0

在'$(document).ready(function(){'如果你添加'console.log(MyVaribale)'你看到控制檯中變量的內容嗎? – 2015-03-25 07:31:51

回答

1

你的Ajax調用的語法是不正確的。看看here,然後試試這個代碼(注意添加{},):

MyVaribale = "Random Data"; 

$(document).ready(function() { 
    $.ajax({ 
     url: '/some/random/url', 
     data : { myVariable : MyVaribale } 
    }); 
}); 
+0

我已經編輯我的文章。這是一個錯字。對不起。 – user2881063 2015-03-25 07:28:52

+0

我發佈的代碼似乎是正確的,你可以在這裏嘗試它(並編輯,如果你想):http://jsfiddle.net/jf3wz8a9/ – Danilo 2015-03-25 07:30:15

+0

是的,我知道代碼是正確的。 ajax調用成功,有時不是。它在服務器上標記錯誤。 – user2881063 2015-03-25 07:32:13

0

你不嘗試一些完全Ajax調用?像這樣。有時候不需要爲MyVariable使用JSON.stringify。

 $.ajax({ 
      url: "/some/random/url", 
      type: 'POST', 
      dataType: 'json', 
      data: JSON.stringify(MyVaribale), 
      contentType: 'application/json', 
      mimeType: 'application/json' 

     }).done(function(data) { 

     }).fail(function(error) { 

     }).always(function(){ 

     });