I hate to be posting a question like this on here, but I’m running out of options for really understanding how this works. In a normal .Net web service, without being configured for JSON or anything, there is the following web method:
<WebMethod()> _
Public Function HelloWorld(ByVal str As Int32) As String
Return "Hello, World! str=" & str
End Function
I would like to make a really simple webpage that would just use JS to call this web method, get the value out of it, and print it in an alert() statement. I’m continuing to research the subject on my own, but I am having a very hard time finding a straight answer to this question.
This is about the closest I’ve been able to come (aside from this not actually using the return value):
<html>
<body>
<script type="text/JavaScript">
<!--
alert("spam");
$.ajax({
type: "POST",
data: "&str=1",
url: "<HTTP path and filename>.asmx/HelloWorld",
timeout: 15000,
cache:false,
success: function (data) {
alert("good");
},
error: function() {
alert("bad");
}
});
alert("spam");
//-->
</script>
</body>
</html>
Again I don’t like posting a question like this on StackOverflow, but I’ve been unable to find a clear, straight answer to this, and I’m very new with JavaScript. Thanks!
EDIT: Throwing a try…catch block around the Ajax call, I get the following message:
$ is not defined
$is a variable. Your code shows that it’s using the jQuery library, using$as an alias.You have to include the jQuery library if you want to use this code.
To do so, include this before your code:
However, if you’re new to javascript, I recommend you first try without jQuery.
For a great tutorial, I can only show you the best resource I know: MDN.
If you absolutely want to use jQuery, you have to know that your
dataparameter is wrong. It does accept a string, but this string isn’t well-formed, it should be this:str=1. Adding another variable would bestr=1&foo=2.jQuery allows you to put an object instead of a string, this provides some syntactic sugar and is generally the recommended way to go (less error-prone):