jquery 错误400当尝试使 AJAX 请求与类型后功能OnPostshiftDataUp

zynd9foi  于 2023-06-29  发布在  jQuery
关注(0)|答案(1)|浏览(176)

我正在使用ASP.NET Core Razor Pages。我得到一个错误时,尝试 AJAX 请求访问OnPostshiftDataUp

ERROR : Failed to load resource: the server responded with a status of 400 () 

console.log(formdata) // serialize data

serverip=172.16.224.999&printername=Zebra2&Location=SupervisorOffice&__RequestVerificationToken=CfDJ8DvYZnvxyLVKi-zvp3jzTImPtgQsnvTBz4ot8mbln2lEaqGcaT_gzZ-KNNfuEBoqHYSBIdcahXL3LLuum4nfTi2oZDQj-PfodyDAVpa45rYEIb7EcRvHrMn71AyB8PMC6DrqvT8q3cCEcSlt1sYQJ-M

但是断点不捕捉这个函数的意思是没有检测到有断点一定要捕捉它
AJAX 请求主要目的是在bootstrap模型上更新数据后保存数据
我为我的代码尝试什么
1-在页面模型上发布类型的函数

public ActionResult OnPostshiftDataUp()
        {

            
            return Content("msg");
           
        }

2- AJAX request to access function or action OnPostshiftDataUp ajax request i do it

$('#save-btn').click(function () {
                var formData = $('#edit-form').serialize();
                console.log(formData);
            
                $.ajax({
                    url: '?handler=shiftDataUp',
                    
         
                    type: "POST",
                  
                    data: JSON.stringify(formData),
            
                   
                    success: function (result) {
                     
                        $('#edit-modal').modal('hide');
       
                        location.reload();
                    },
                    error: function (xhr, status, error) {
                        console.log(error);
                    }
                });
            });

bootstrap模型然后发送 AJAX 请求时,点击按钮保存

<div class="modal fade" id="editshelflabelModal" tabindex="-1" role="dialog" aria-labelledby="userDetailsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <h5 class="modal-title" style="text-align:center;">
                @*<img src="@Url.Content("~/Img/UserProfile1.png")" alt="ImageProfile" style="width:22%;height:10%" />*@

            </h5>
            <div class="modal-header">
                <h5 class="modal-title" id="editshelflabelModaldata" style="margin-left:200px;">Hi,@TempData["UserID"]</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                  <form id="edit-form" method="post">
                  @*  <input type="hidden" id="edit-id" name="ShiftId">*@
                    <div class="form-group">
                        <label for="edit-server">Server IP</label>
                        <input type="text" class="form-control" id="edit-ip" name="serverip">
                    </div>
                    <div class="form-group">
                        <label for="edit-printer">Printer Name</label>
                        <input type="text" class="form-control" id="edit-printername" name="printername">
                    </div>
                    <div class="form-group">
                        <label for="edit-locationsdata">Location Name</label>
                        <input type="text" class="form-control" id="edit-Location" value="save" name="Location">
                    </div>
                </form>
                @*<div class="form-group row">
                    <label for="serverIp" class="col-sm-1 col-form-label" style="font-size:15px;font-family: 'Open Sans', sans-serif;font-weight: bold;">Server IP</label>
                    <div class="col-sm-3">
                        <input id="serverIp" asp-for="User.UserName" readonly type="text" class="form-control" style=" margin-left:10px;font-size:15px;font-family: 'Open Sans' , sans-serif;font-weight: bold;" maxlength="30" />
                    </div>
                </div>
            

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary" id="save-btn">Save changes</button>
            </div>
        </div>
    </div>
</div>

最新文章

应用以下答案后仍存在问题:

错误显示加载资源失败:服务器以状态400()响应

所以我做什么来解决错误

最后更新后问题到现在还没有解决,你可以请帮助我发送完整的样本与引导模型和jQuery和HTML表可能是我有问题的一些部分,请
从下面的代码请求成功完成,但函数post PostshiftDataUp()未缓存或点击保存按钮后命中

完整的代码样本我尝试什么

program.cs
builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");   

 public class ShelfLabelPrinterSetUpModel : PageModel
    {
 [BindProperty]
        public string serverip { get; set; }
        [BindProperty]
        public string printername { get; set; }
        [BindProperty]
        public string Location { get; set; }
public IActionResult OnPostshiftDataUp(string serverip, string printername, string location)
        {
            return new JsonResult("Success");

        }
}
<div class="modal fade" id="editshelflabelModal" tabindex="-1" role="dialog" aria-labelledby="userDetailsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <h5 class="modal-title" style="text-align:center;">
               

            </h5>
            <div class="modal-header">
                <h5 class="modal-title" id="editshelflabelModaldata" style="margin-left:200px;">Hi,@TempData["UserID"]</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="edit-form" method="post">
                    <div class="form-group">
                        <label for="edit-server">Server IP</label>
                        <input type="text" class="form-control" id="edit-ip" name="serverip">
                    </div>
                    <div class="form-group">
                        <label for="edit-printer">Printer Name</label>
                        <input type="text" class="form-control" id="edit-printername" name="printername">
                    </div>
                    <div class="form-group">
                        <label for="edit-locationsdata">Location Name</label>
                        <input type="text" class="form-control" id="edit-Location"  name="Location">
                    </div>
                    <button type="button" class="btn btn-primary" id="save-btn">Save changes</button>
                </form>
              
                <a href="/"><i class="fas fa-sign-out-alt"></i> Sign Out</a>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
              
            </div>
        </div>
    </div>
</div>
<table id="editbootstarp">
    <thead>
        <tr>
            <th style="display:none;">ID</th>
            <th>BranchType</th>
            <th>UserPC</th>
            <th>PrinterName</th>
            <th>ArabicConfig</th>
            <th>Status</th>
            <th>Location Name</th>
            <th>>Action</th>
        </tr>
    </thead>
    <tbody>
        
        @foreach (DataRow row in table.Rows)
        {
            <tr>
                <td style="display:none;">@row["AutoID"]</td>
                <td>@row["BranchType"]</td>
                <td>@row["UserPC"]</td>

                 <td>@row["PrinterName"]</td>
                <td>@row["ArabicConfig"]</td>
                <td>@row["Status"]</td>
                <td>@row["DisplayName"]</td>
                <td>
               <button class="editbt"   data.Location="@row["DisplayName"]" data.printername="@row["PrinterName"]" data.serverip="@row["UserPC"]">Edit</button>
             </td>  
            </tr>
        }
    </tbody>
</table>
@section scripts {
    <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
    <script src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">

$(document).ready(function(){
  $('#editbootstarp tbody').on('click', 'tr', function () {
                // Get the data from the clicked row
                var rowData = $(this).children('td').map(function () {
                    return $(this).text();
                }).get();
                $('#editshelflabelModal #edit-ip').val(rowData[2]);
                $('#editshelflabelModal #edit-printername').val(rowData[3]);
                $('#editshelflabelModal #edit-Location').val(rowData[6]);
                $('#editshelflabelModal').modal('show');
            });
  $('#save-btn').click(function () {
                var formData = $('#edit-form').serialize();
                console.log(formData);
                $.ajax({
                    url: '?handler=shiftDataUp',
                    type: "POST",
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("XSRF-TOKEN",
                            $('input:hidden[name="__RequestVerificationToken"]').val());
                    },
                    data:formData,
                    success: function (result) {
                        alert(result);
                    },
                    error: function (xhr, status, error) {
                        console.log(error);
                    }
                });
            });
            
    });
 });

更多详情

network tool browser gool chrome result also请求URL:https://localhost:7160/ShelfLabelPrinterSetUp?handler=shiftDataUp请求方法:开机自检状态代码:200远程地址:[::1]:7160推荐人策略:交叉原点时严格原点

slwdgvem

slwdgvem1#

您收到一个400 Bad Request,因为您没有通过Razor Pages默认内置的反请求伪造检查:https://www.learnrazorpages.com/security/request-verification
当您将表单数据转换为JSON时,请求验证令牌作为JSON有效负载的一部分隐藏在请求主体中。Razor Pages无法在这种情况下读取令牌,因此您需要在头中发送请求验证令牌:

$.ajax({
    url: '?handler=shiftDataUp',
    type: "POST",
    contentType: "application/json",
    headers: {
        "RequestVerificationToken" : $('[name="__RequestVerificationToken"]').val()
    },
    data: JSON.stringify(formData)
    ...

或者,不要将表单序列化为JSON。按原样发送:

$.ajax({
        url: '?handler=shiftDataUp',
        type: "POST",
        data: $('#edit-form').serialize()
        ...

相关问题