2015-11-18 44 views
0

我正在使用CakePHP作爲後端,JQuery作爲前端的Web應用程序。爲了與服務器進行通信,我已經創建了表單和jQuery Ajax以及顯示Ajax向網絡中的url發送請求值的瀏覽器。以下是我現在所擁有的:Jquery Ajax Post到CakePHP控制器

問題

I want to display ajax post value into add.ctp which is not showing 

1凡Ajax是工作

<script type="text/x-javascript"> 
$(".hover-star").click(function() { 
$("#hover-test").css("color", "#ff6a00"); 

    var id= $('input[name=starrating]:checked').attr('id'); 

    $.ajax({ 
     type: "POST", 
     url: '<?php echo Router::url(array('controller'=>'Reviews','action'=>'add'));?>', 
     cache: false, 
     data: "id="+id, 
     dataType: 'HTML', 
     success: function(result) { 
      window.open('/app/webroot/reviews/add/'+id,'_self'); 

     },  
     error: function (response, desc, exception) { 
      // custom error 
     } 
    }); 
}); 
</script> 

<form method="post"> 
    <input class="hover-star" type="radio" name="starrating" id="1" value="1" title=""/> 
    <input class="hover-star" type="radio" name="starrating" id="2" value="3" title=""/>  
    <input class="hover-star" type="radio" name="starrating" id="3" value="3" title=""/>  
</form> 

第2頁,我想顯示AJAX請求的值添加。 ctp

<?php echo $this->ratingPost;?> 

評論控制器添加功能

function add() 
{  
    $this->ratingPost= $data = $this->data; 
} 
+0

什麼錯誤? –

+0

@AbrarKhan沒有錯誤,但鉻瀏覽器網絡顯示,在點擊單選按鈕 –

回答

0

在頁面,Ajax是工作

<div id="show"></div> 

阿賈克斯成功會像

success: function (result) { 
       $("#show").html(result); 
       $("#show").show(); 
      } 
+0

值'

'後顯示ajax發送值和'add.ctp'文件中沒有值顯示,但爲什麼值不顯示在'add.ctp'中不打印或在'controller.php'文件中回顯 –

+0

你的蛋糕版? –

+1

cakephp版本是2.0.13 –

2

它看起來像有可能是幾件事情出錯了。首先,您需要了解AJAX會將其數據發佈到指定的URL並等待來自服務器的響應。答覆將包含在「結果」中。

在這個例子中,它看起來像是POSTing到/ reviews/add。當你這樣做的時候,你的add方法會收到post數據並嘗試渲染add.ctp視圖文件。這整個渲染是返回到您的AJAX成功「結果」。在你的add方法中,你沒有對視圖設置任何東西,並且你沒有返回任何值,所以你的「結果」是空的。

在您的AJAX成功中,您試圖打開一個新的窗口,該窗口再次調用add方法,並且您試圖包含參數「id」,該參數不會對返回的結果做任何事情,只嘗試使用給定的參數再次運行該方法,但你的方法並不要求任何參數...

如果你想要一個新的窗口打開與點擊一個id值,爲什麼即使使用AJAX,只是發送該id作爲您的add方法的參數。通常我會認爲AJAX用於動態更新當前加載的頁面上的內容。我將在您的代碼中重點介紹我在下面討論的內容。

腳本

<script type="text/x-javascript"> 
    $(".hover-star").click(function() { 
    $("#hover-test").css("color", "#ff6a00"); 
    var id= $('input[name=starrating]:checked').attr('id'); 

    window.open('/app/webroot/reviews/add/'+id, '_self'); 
    } 
</script> 

你添加方法

public function add($myID=null){ 
    $this->set('myID', $myID); 
} 

如果你致力於AJAX,你可以做這樣通過創建一個新的方法來處理渲染返回的AJAX。我只是不明白這一點。您還必須將您從AJAX方法返回的內容限制爲URL安全編碼。

AJAX方式

$.ajax({ 
    type: "POST", 
    url: '<?php echo Router::url(array('controller'=>'Reviews','action'=>'add'));?>', 
    cache: false, 
    data: "id="+id, 
    dataType: 'HTML', 
    success: function(result) { 
     window.open('** path to new method for rendering view **'+result, '_self'); 
    },  
    error: function (response, desc, exception) { 
     // custom error 
    } 
}); 
+0

謝謝jadedcore –