AJAX返回未定义

时间:2016-07-10 20:38:16

标签: jquery ajax asp.net-mvc

请从我的MVC视图中查看以下代码:

<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>

    <script type="text/javascript">
        function GetMessage() {
            $.ajax({
                type: "GET",
                url: "http://localhost/webapi/api/Values/",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess(),
                async: false,
                failure: function (response) {
                    alert('there was an error creating the disposal decision records')
                }
            });

            function OnSuccess() {
                return function (response) {
                    alert(response.d);
                }
            }
        }
        GetMessage();
    </script>

以及来自http://localhost/webapi/api/Values/的代码:

public Person Get()
        {
            Person p = new Person();
            p.id = 1;
            p.name = "Bert";
            p.age = 31
            return p;
        }

在Success事件处理程序中;提示未定义。为什么呢?

2 个答案:

答案 0 :(得分:0)

每当您使用WebApi或任何其他Web服务时,必须先使用jquery-ajax在浏览器中对其进行测试

首先,您需要在浏览器中尝试http://localhost/webapi/api/Values/(以确保您的服务器端正常,因为它不需要您的jquery ajax代码)。可能你不会得到理想的结果。

现在无论如何你需要对ajax请求进行一些修复,请按照

进行操作
<script type="text/javascript">
    var OnSuccess = function(data)
    {
         alert("this is success"); // just check if this works
         alert(data); // just check if this works
         if(data && data.d)
            alert(data.d);
    }

    function GetMessage() {
        $.ajax({
            type: "GET",
            url: "http://localhost/webapi/api/Values/",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            async: false,
            error:function(er){ 
                 alert(er.responseText);
            }                
        });

        function OnSuccess() {
            return function (response) {
                alert(response.d);
            }
        }
    }
    GetMessage();
</script>

如果http://localhost/webapi/api/Values/适用于您的浏览器,那么在上述修复后,ajax也必须正常运行。但如果没有,那么你需要考虑以下

您的服务器端似乎还不行。您的服务器端控制器必须具有类似

的代码
[RoutePrefix("api/Values")]
public class PersonssController : ApiController
{
    // GET api/Values
    [Route("")]
    public Person Get() { 
    {
        Person p = new Person();
        p.id = 1;
        p.name = "Bert";
        p.age = 31
        return p;
    }    
}

在您的webapi控制器进行了上述更改之后,现在您应该能够在浏览器中找到http://localhost/webapi/api/Values/正常工作,并且因为您已经更改了我在顶部告诉的jquery请求,所以一切都很好

答案 1 :(得分:-1)

试试这个:

    var OnSuccess = function(response) {
       alert(response.d);
    }

并在你的ajax电话中:

success: OnSuccess,
相关问题