【发布时间】:2014-06-26 18:46:56
【问题描述】:
我创建了一个简单的 ASP.NET Web 应用程序,带有一个基本的 Web 服务。在客户端,我有 Javascript 代码,它使用 AJAX 从 web 服务中检索数据。
我的网络服务生成一个包含一些基本数据(姓名、街道、电话)的学生对象,并通过 JS 调用将其发送给客户端。
客户端有一个按钮,通过 JS 触发对 web 服务的调用。
我的问题是,当我单击 JS 按钮从 web 服务获取数据时,我总是收到与我的 JS web 服务调用函数相关的错误消息:
“JavaScript 运行时错误:无法获取未定义或空引用的属性 'GetStudentId'”
我该如何解决这个问题?
我的 home.aspx 页面:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="home.aspx.cs" Inherits="Ajax_testing.home" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<%--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>--%>
<script type="text/javascript" src="script/myjs.js"></script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/jsonwebservice.asmx" />
</Services>
</asp:ScriptManager>
<button onclick="GetStudentById()" type="button">GET AJAX DATA FROM WEBSERVICE</button>
<a href="jsonwebservice.asmx">to JSON webservice</a>
<div id="myTestDiv">
</div>
<div id="jsontest">
</div>
</form>
</body>
</html>
我的webservice jsonwebservice.asmx(不要介意文件的json前缀名)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace Ajax_testing
{
/// <summary>
/// Summary description for jsonwebservice
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class jsonwebservice : System.Web.Services.WebService
{
[WebMethod]
public Student GetStudentId()
{
Student student = new Student();
student.name = "S.L. Holmes";
student.street = "baker street";
student.phone = "27673627";
return student;
}
}
public class Student
{
public string name { get; set; }
public string street { get; set; }
public string phone { get; set; }
}
}
我的 java 脚本:myjs.js
function GetStudentById() {
Ajax_testing.jasonwebservice.GetStudentId(GetStudentByIdSuccessCallBack,
GetStudentByIdFailedCallback);
//*******correction: jasonwebservice -> jsonwebservice****
}
function GetStudentByIdSuccessCallBack(results) {
document.getElementById("myTestDiv").innerHTML = "JSON webservice <br/> " + results.name + "<br/>" + results.street + "<br/>" + results.phone + "<br/>";
}
function GetStudentByIdFailedCallback(errors) {
alert(errors.get_message());
}
【问题讨论】:
标签: javascript asp.net ajax web-services soap