Can't call function using ajax

前端 未结 3 1199
眼角桃花
眼角桃花 2021-01-29 09:05

I\'m trying to call a function using ajax, but it\'s not responding.

Here is the Code:

相关标签:
3条回答
  • 2021-01-29 09:10

    Ensure That jQuery Is Working

    Firstly, ensure that your jQuery code is working properly and is referenced. You'll need to include a reference to the library prior to calling any jQuery-related code :

    <!-- Example Reference -->
    <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
    <script>
        $(function(){
              // Place your code here
        });
    </script> 
    

    If you want to perform a GET...

    You are specifying within your ajax() call that you are making a POST request via the type attribute, but your Controller Action is explicitly expecting a GET via the [HttpGet] attribute decorating your action.

    You can resolve this by changing your type attribute from POST to GET (or you could remove it entirely as GET is the default):

    type: "GET",
    

    If you want to perform a POST...

    Alternatively, if you want to actually perform a POST, then just keep your existing code and use the [HttpPost] attribute instead :

    [HttpPost]
    public ActionResult Remove(int? Book_id)
    {
         // Code omitted for brevity
    }
    
    0 讨论(0)
  • 2021-01-29 09:17

    You can also call the Controller via Ajax by passing parameter(s) as shown below:

    <script type="text/javascript">
    $('.Remove').click(function () {
        $.ajax({
            url: '@Url.Action("Remove", "ReadingNow")',
            data: { myId: $(this).data('id') /* add other additional parameters */ }, 
            cache: false,
            type: "POST",
            success: function (response) {
                $('#myElem').html(response).fadeIn('slow');
                $('#myElem').delay(8000).fadeOut('slow');
            },
            failure: function (response) {
                alert("Failure");
            }
        });
    });
    </script>
    
    0 讨论(0)
  • 2021-01-29 09:27

    i thing the problem is in this line:

    url: '@Url.Action("Remove", "ReadingNow")?Book_id=' + myId

    dont use @Url.Action that is not the current syntax to use razor in JS (you need to use the pseudo-element), just write the url ["/ReadingNow/Remove?Book_id="+id]. that way you know for sure where the request will go and it easier to read.

    0 讨论(0)
提交回复
热议问题