2013-08-21 36 views
0

我正在嘗試使用AJAX發佈表單數據並在div中顯示結果。儘管我盡了最大的努力,但我失敗了。jQuery表單提交和顯示結果不起作用

這裏是我與jQuery使用的代碼1.8.3

HTML:

<form action="" method="post" id="forecastform"> 
    <input type="text" name="weatherloc" class="weatherloc"> 
    <input type="submit" name="weathersubmit" class="weathersubmit" value="Get Forecast"> 
</form> 

<div class="wfposts"></div> 

的JavaScript在頭部分:

 <script type="text/javascript"> 
      jQuery('#forecastform').submit(function(event) { 
      event.preventDefault(); 
      var term = jQuery('.weatherloc').val(); 
      var url = <?php echo get_template_directory_uri() . '/local-forecast-process.php';?>; 

       var posting = jQuery.post(url, { weatherloc: term }); 

        posting.done(function(data) { 
        var content = jQuery(data); 
        jQuery(".wfposts").empty().append(content); 
        }); 
      }); 
     </script> 

首先,頁面重新加載忽略event.preventDefault();
我不確定是否正在發送數據,因爲在頁面加載後div未被填充。

有人請幫助

回答

2

語法錯誤,未加引號的字符串!

替換:

var url = <?php echo get_template_directory_uri() . '/local-forecast-process.php';?>; 

var url = "<?php echo get_template_directory_uri(); ?>/local-forecast-process.php"; 

,並添加一個DOM準備處理程序,如果元素後不包含的JavaScript。

+0

謝謝,它的工作..對不起,再次打擾,有沒有什麼辦法可以添加ajax加載圖像與此代碼? – Abhik

+0

@Abhik - 當然,像這樣 - > http://jsfiddle.net/Jnm8A/ – adeneo

+0

真棒!你讓我今天一整天都感覺很好。 – Abhik

2

您自元素forecastform在$。就緒包這件事是不是有當jQuery是試圖將其選中。

$(document).ready(function(){ 
    jQuery('#forecastform').submit(function(event) { 
    .... 
    ... 
    }) 
}