簡體   English   中英

無響應Ajax請求symfony2

[英]No response Ajax request symfony2

發出ajax POST請求,什么也沒回來:

這是我的ajax請求:

$.ajax({
        method: 'POST',
        url: "{{ path('app-like-add') }}",
        data: { imageId: id },
        success: function(response) {
            if (response == 'success') {
                $('#'+ id).removeClass('like');
                $('#'+ id).addClass("like-success");
            } else {
                alert('no :(');
            }
        },
        error: function(response){
            alert('fail');
            console.log(response);
        }
    });

如何通過相應的函數調用此控制器:

class LikeController extends Controller {

  public function addAction(Request $request)
  {
    return new JsonResponse('success');
  }
}

但是我什么也沒得到,那奇怪的是我得到了200 OK。

Ajax響應

路由的定義如下:

app-like-add:
pattern:               /add-like
defaults:              { _controller: AppBundle:Like:add }

您的路徑未解釋,請查看請求網址,您擁有app-like-add ,而不是等效的網址。 為避免此錯誤,您必須放入完整路徑或安裝捆綁包以完整網址替換路徑,例如FosJsRoutingBundle

https://github.com/FriendsOfSymfony/FOSJsRoutingBundle

此捆綁包使您可以在JavaScript代碼中公開路由。 這意味着您將能夠使用給定的參數生成URL,就像使用Symfony2核心中提供的Router組件一樣。

在您的Yaml中:

app-like-add:
    pattern:               /add-like
    defaults:              { _controller: AppBundle:Like:add }
    options:
        expose: true

在JS代碼中:

Routing.generate('app-like-add')

您傳遞的URL不正確,請更改為常規URL

url: "/add-like"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM