weixin_33728268 2017-05-02 07:12 采纳率: 0%
浏览 117

MVC控制器返回JSON

I have this HTML and script :

<form>
    Text :<br>
    <input type="text" name="nameid" id="nameid" value="">
    <br><br>
    <input type="submit" value="Send">
</form> 

$(document).ready(function () {

    $("form").submit(function (event) {
        $.ajax({
            type: 'GET',
            url: "/MyController/MyAction2",
           data: { nameid: $('#nameid').val() },
            success: function (newdata) {
                var cy = cytoscape({
                    container: document.getElementById("cy"),
                    elements: JSON.parse(newdata)

                });
                });
            }
        });

    });

});

When MyAction2 is called from AJAX, the url goes to MyAction2 and I see raw JSON data. How can I make MyAction2 returns value to the AJAX and I would use it as newdata variable? Thanks.

  • 写回答

1条回答 默认 最新

  • 旧行李 2017-05-02 07:16
    关注

    The code you've used to get JSON data is correct, you just need to stop the form submission, which you can do by calling preventDefault() on the event.

    Also note that you have a mis-matched }); in the question but I assume this is just a typo in the question itself. Also note that you don't need to manually JSON.parse the response if you set the correct dataType. Try this:

    $(document).ready(function () {
      $("form").submit(function (event) {
        event.preventDefault(); // < add this...
    
        $.ajax({
          type: 'GET',
          url: "/MyController/MyAction2",
          data: { nameid: $('#nameid').val() },
          dataType: 'json', 
          success: function (newdata) {
            var cy = cytoscape({
              container: document.getElementById("cy"),
              elements: newdata
            });
          }
        });
      });
    });
    
    评论

报告相同问题?