1

私はajaxがあまり得意ではありませんが、jqueryプラグインの1つを使用するには、ajaxで少し呼び出す必要があります。問題は、それが常に関数のエラー処理に含まれることであり、その理由はわかりません。Visual Web Developper Expressを使用しているため、JavaScriptのデバッグが機能しません。

jquery関数は次のとおりです。

$('.auto-submit-star').rating({
            callback: function (value, link) {
                $.ajax({
                    type: "POST",
                    url: "/Recipe/Rate",
                    data: $("#rate").serialize(),
                    dataType: "text/plain",
                    success: function (response) {
                        if (response != 'false') {
                            alert('Your vote has been saved');
                        } else {
                            alert('You already voted for this recipe!');
                        }
                    },
                    error: function (response) {
                        alert('There is an error');
                    }
                });
            }
        });

次に、それはコントローラーに入ります。私はこの部分をデバッグしました、そしてそれは働きます、それはデータベースに良い値を保存し、そしてユーザーがすでに投票したかどうかに応じて「false」または「」を返します。

コードは次のとおりです。

[HttpPost]
        [Authorize]
        public ActionResult Rate(FormCollection form)
        {
            var rate = Convert.ToInt32(form["Score"]);
            var id = Convert.ToInt32(form["IDRecipe"]);

            //On valide si l'utilisateur a déja voté
            Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey;
            var existingVote = db.StarRatings.Where(a => a.IDRecipe == id).Where(b => b.IDUser == userGuid).FirstOrDefault();

            if (existingVote != null)
                return Content("false");

            StarRating rating = new StarRating();
            rating.IDRecipe = id;
            rating.IDUser = (Guid)Membership.GetUser().ProviderUserKey;
            rating.Score = rate;

            var recipe = db.Recipes.Where(a => a.IDRecipe == id).First();
            recipe.StarRatings.Add(rating);
            db.SaveChanges();

            return Content("");
        }

なぜ私がいつも「エラーがあります」というメッセージを受け取り、それがajax呼び出しの「成功」部分に入らないのか、誰でも教えてくれますか?コントローラーに何か特別なものを返す必要がありますか?

編集

これは、コメントの1つで私が発見したInternetExplorerデバッガーの応答変数のスクリーンショットです。

スクリーンショット!

ありがとう!

4

2 に答える 2

2

I would suggest the following changes:

[HttpPost]
[Authorize]
public JsonResult Rate(int Score, int IDRecipe)
{
    //On valide si l'utilisateur a déja voté
    Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey;
    var existingVote = db.StarRatings.Where(a => a.IDRecipe == IDRecipe).Where(b => b.IDUser == userGuid).FirstOrDefault();

    if (existingVote != null)
        return Json(false);

    StarRating rating = new StarRating();
    rating.IDRecipe = IDRecipe;
    rating.IDUser = (Guid)Membership.GetUser().ProviderUserKey;
    rating.Score = Score;

    var recipe = db.Recipes.Where(a => a.IDRecipe == IDRecipe).First();
    recipe.StarRatings.Add(Score);
    db.SaveChanges();

    return Json(true);
}

And your JavaScript call:

$('.auto-submit-star').rating({
    callback: function (value, link) {
        $.ajax({
            type: "POST",
            url: "/Recipe/Rate",
            data: { IDRecipe: GetRecipeID(), Score: GetScore() },
            cache: false,
            success: function (response) {
                alert(response);
            },
            error: function (xhr, error) {
                alert(error);
            }
        });
    }
});

The data object value passed to the $.ajax call will be appended to the URL as a set of query parameters, resulting in a URL similar to /Recipe/Rate?IDRecipe=123&Score=123 which is interpreted by the MVC code to find the appropriate parameters to initialize in the call to the Rate method. Similarly, the Json(true) and Json(false) returns in the Rate method will be converted to a JSON-encoded string and returned as the body of the response.

于 2013-02-19T02:09:48.553 に答える
1

textこれを再現し、の代わりにを使用して修正することができましたtext/plain。原因についての私の理解は、ブラウザが最初に応答をHTMLとして解釈し、結果としてエラーをスローしているということです。コンソールでコードを実行し、コントローラーが返した「予期しないトークンB」というテキスト「Blah」が検出されたときに解析エラーを確認できます。

Firefoxの問題への参照以外に、これに関する確かなドキュメントは見つかりませんでしたが、Chromeを使用していて、同じ問題が発生しました。xhr.overrideMimeType("text/plain; charset=x-user-defined");回避策は、ここに記載されているhttp://api.jquery.com/jQuery.ajax/を使用することでした。ブラウザがまだテキストを好まない場合は、代わりにそれを行う必要があるかもしれません。

                $.ajax({
                    type: "POST",
                    url: "/Recipe/Rate",
                    data: $("#rate").serialize(),
                    dataType: "text",
                    success: function (response) {
                        if (response != 'false') {
                            alert('Your vote has been saved');
                        } else {
                            alert('You already voted for this recipe!');
                        }
                    },
                    error: function (response) {
                        alert('There is an error');
                    }
                });
于 2013-02-19T02:21:52.533 に答える