$ .ajaxSetUp不工作

时间:2015-01-03 17:48:06

标签: jquery ajax

我得到了$ .ajaxSetUp(),其中我定义了标题。当发出ajax请求时,我希望ajax能够传递$ .ajaxSetUp中定义的这些头以及该请求。但它没有发生。

例如:我有两个按钮,我希望标题将与这两个事件一起发送。但它没有发生。如何发送标题以及这些请求。

 function ajaxSetUp() {
    $.ajaxSetup({
        cache: false,
        headers: { "CustomHeader": "Value1" },
    });
}

$('#btn').click(function () {
    $.ajax({
        url: 'HOME/POSTSAMPLEACTION',
        type: "POST",
        data: { name: "test" },
        async: true,
        dataType: "json",
        //headers: {
        //    'VerificationToken': forgeryId
        //},
        success: function (returnVal) {
            alert(returnVal);
        },
        error: function (data) {
            alert("failed");
        },
    });
});


$('#btn1').click(function () {
   $.ajax({
    url: 'HOME/ADDACTION',
    type: "POST",
    data: { name: "test" },
    async: true,
    dataType: "json",
    //headers: {
    //    'VerificationToken': forgeryId
    //},
    success: function (returnVal) {
        alert(returnVal);
    },
    error: function (data) {
        alert("failed");
    },
   });

});

     [AjaxValidateAntiForgeryToken]
    public JsonResult PostSampleAction(string name)
    {
        return this.Json("Post Passed Validation -" + name);
    }

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;

 namespace AntiForgerySample
 {
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class AjaxValidateAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
   public void OnAuthorization(AuthorizationContext filterContext)
    {
        try
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest()) // if it is ajax request.
            {
                this.ValidateRequestHeader(filterContext.HttpContext.Request); // run the validation.
            }
            else
            {
                AntiForgery.Validate();
            }
        }
        catch (HttpAntiForgeryException e)
        {
            throw new HttpAntiForgeryException("Anti forgery token not found");
        }
    }

 private void ValidateRequestHeader(HttpRequestBase request)
    {
        string cookieToken = string.Empty;
        string formToken = string.Empty;
        string customHeader = string.Empty;
        string tokenValue = request.Headers["VerificationToken"]; // read the header key and validate the tokens.
        customHeader = request.Headers["CustomHeader"];
        if (!string.IsNullOrEmpty(tokenValue))
        {
            string[] tokens = tokenValue.Split(',');
            if (tokens.Length == 2)
            {
                cookieToken = tokens[0].Trim();
                formToken = tokens[1].Trim();
            }
        }

        AntiForgery.Validate(cookieToken, formToken); // this validates the request    token.
    }
}

}

1 个答案:

答案 0 :(得分:0)

尝试

// default options
$.ajaxSetup({
    cache: false,
    headers: { "CustomHeader": "Value1" },
    url: 'HOME/POSTSAMPLEACTION',
    type: "POST",
    data: { name: "test" },
    async: true,
    dataType: "json",
    success: function (returnVal) {
        alert(returnVal);
    },
    error: function (data) {
        alert("failed");
    }
});

$('#btn').click(function () {
  // pass custom options here , if required , 
  // to override default options at `$.ajaxSetup`
  $.ajax();
});