12.10. AJAX Methods

It is very common for performance optimization to need to retrieve data or code from an external source after a page is loaded. jQuery makes this very easy.

12.10.1. Load and Run JavaScript File

The following code loads an external JavaScript file called test.js and then executes it:

$.ajax({
    type: "GET",
    url: "test.js",
    dataType: "script"
});

The test.js file consists of just the following line:

alert('hello'),

12.10.2. Submitting Data

You often need to submit data to another web page. You can easily do this with the following code:

$.ajax({
    type: "POST",
    url: "myForm.aspx",
    data: "firstname=Alex&lastname=Mackey",
    success:
    function() {
        alert("form submitted");
    }
});

You will use this functionality in the ASP.NET MVC example (see Chapter 13) to submit your form data:

//Submit client side
$.ajax({
    type:
    "POST",
    dataType: "json",
    url: "Edit",
    data: { Description: InputDescription, Length: InputLength,
            DateShowing: InputDateShowing },
    success: function(result) {
        alert(result.Message +  " adding film at " + result.DateShowing);
    },
    error: function(error) {
        alert('error '),
    }
});

12.10.3. Getting the Latest Version of a Page

You can retrieve the contents of a page in the same domain as the calling page with a few lines of code. This could be useful in Ajax scenarios in which you want to load content behind the scenes:

$.ajax({
    url: "default2.aspx",
    cache: false,
    success: function(returnHtml) {
        $("#div1").append(returnHtml);
    }
});

12.10.4. Retrieving a JSON Object

JSON is a compact format for representing data. jQuery contains support for working with JSON objects. You will first create a page called default2.aspx that will return a JSON-formatted string (you will soon look at a better way of doing this):

  1. Right-click your solution, add a new page called default2.aspx, and choose to place your code in a separate file.

  2. Remove all the code in default2.aspx except for the page declaration.

  3. Add the following code to default2.aspx.cs:

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Buffer = true;
        Response.Clear();
        Response.ContentType = "application/json";
        Response.Write("{firstName: "Alex",lastName: "Mackey"}");
    }

  4. Open default.htm, and alter the helloJQuery() function to the following (note that you pass a URL to which you send the query and then a function to be called when the query is completed):

    $.getJSON("default2.aspx",
        function (data) {
            alert(data.firstName);
        }
    );

  5. Press F5 to run the project.

  6. Click the Hello jQuery button.

You should see an alert box displaying "Alex" (the firstName property from the JSON object).

12.10.5. A Better Way

Visual Studio 2008 (and later) offers a better way:

  1. Create a new page called default3.aspx, and then open default3.aspx.cs.

  2. Add the following using statement:

    using System.Web.Services;

  3. Add the following class to represent your returned object:

    public class Person
        {
            public string firstName {get; set;}
            public string lastName { get; set; }
        }

  4. Now add a new method to your page marked with the [WebMethod] attribute to expose it to the client script:

    [WebMethod]
    public static Person GetFirstname()
    {
        Person p = new Person();
        p.firstName = "Alex";
        p.lastName = "Mackey";
    
         return p;
    }

  5. Now amend the existing jQuery code to the following:

    $.ajax({
        type: "POST",
        url: "Default3.aspx/GetFirstname",
        data: "{}",
        contentType: "application/json",
        dataType: "json",
        success: function (input) {
            alert(input.d.firstName);
        }
    });

That's much easier—and safer. Note that you had to access the d property in order to access the firstName property. This is to prevent the execution of the returned string as a script. For more information on this issue, please refer to http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.66.132