於jQuery使用ajax jQuery.get()、jQuery.post() 技術
一、.get技術
syntax:jQuery.get( url [, data ] [, success ] [, dataType ] )
<!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> $(document).ready(function () { $("button").click(function () { $.get("http://www.w3schools.com/jquery/demo_test.asp", function (data, status) { $("#myText").text("Data: " + data + " Status: " + status); },"html"); }); }); </script> </head> <body> <p id="myText">a Text</p> <button>Send an HTTP GET request to a page and get the result back</button> </body> </html>
demo_test.asp檔案內容為
This is some text from an external ASP file.
1、先來看sucess function function (data, status,dataType){}
(1).當使用.get()方法去server端get資料成功後,會把相關資訊放在第一参數(data)與第二參數(status)。
(2).其中的function(data,status,dataType){...},data與status、dataType参數的變數命名式可以隨意取的。
(3).最主要是變數的順序不能動,第一参數為server端回傳的內容,第二參數為http狀態,第三個參數為回傳資料預定格式。
(4).這三個參數都是optional的。
(5)第三個參數可指定為json、xml、html等。
2、此程式的動作為當按下按鈕時,a Text文字會被替換成This is some text from an external ASP file.
當你在測試的時候卻發現無法動作,如果你有按F12打開console查看錯誤訊息時,就會發現
「XMLHttpRequest cannot load http://www.w3schools.com/jquery/demo_test.asp.
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://null.jsbin.com' is therefore not allowed access.」
這段錯誤訊息,主要原因為當傳輸方式使用get或post時,伺服端並沒有允許你擁有跨網站存取權限,
所以按下按鈕去get資料回來卻是失敗的。
測試網址如下:
http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_ajax_get
3、另外jQuery還有$("selector").get();語法,
這是用來取得該element的object,是個完全不同的東西。
二、post技術
1、$.post()
syntax:$.post(URL,data,callback);
<!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> $(document).ready(function () { $("button").click(function () { $.post("demo_test_post.asp", { name: "Donald Duck", city: "Duckburg" }, function (data, status) { $("#myText").text("Data: " + data + " Status: " + status); }); }); }); </script> </head> <body> <p id="myText">a Text</p> <button>Send an HTTP POST request to a page and get the result back</button> </body> </html>
此程式的功能為按下按鈕時,將name與city所設定的值post到server端並取得所吐回的資料再秀出來。
測試網址如下:
http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_ajax_post
2、$.ajax()
$.post()相當等於$.ajax(),用法大致相同唯有ajax的type要指定為post,範例如下
$.ajax({ type: "POST", url: url, data: data, success: success, dataType: dataType });
3、MVC範例-使用post技術
此範例文章過長,僅供參考
(1)、Model
namespace WebApplication1.Models
{
using System.ComponentModel.DataAnnotations;
public partial class ACTICLE
{
public int Id { get; set; }
[Display(Name = "種類")]
public string type { get; set; }
[DataType(DataType.Date)]
[Display(Name = "日期")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public System.DateTime date { get; set; }
[RegularExpression("^.{1,30}$", ErrorMessage = "Invalid string")]
[Display(Name = "標題")]
public string title { get; set; }
[Display(Name = "內文")]
public string context { get; set; }
}
}
(2)、Controller
using System;
using System.Collections.Generic;
using System.Web.Mvc;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
// GET: ACTICLEs/Create
public ActionResult Create()
{
var a = new ACTICLE();
a.context = "context";
a.date = DateTime.Now;
a.title = "title";
a.type = "type";
ViewBag.type = new List<string>() { "公告訊息", "公益活動" };
return View(a);
}
// POST: ACTICLEs/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
public ActionResult Create([Bind(Include = "Id,type,date,title,context")] ACTICLE aCTICLE)
{
try
{
if (ModelState.IsValid)
{
db.ACTICLESet.Add(aCTICLE);
db.SaveChanges();
return RedirectToAction("Index");
}
return View();//前端已重新導向,此行較無作用
}
catch (Exception ex)
{
System.Data.Entity.Validation.DbEntityValidationException DbEntityValidationException = (System.Data.Entity.Validation.DbEntityValidationException)ex;
throw DbEntityValidationException;
}
}
}
}
(3)、View
@model WebApplication1.Models.ACTICLE
@{
ViewBag.Title = "Create";
var selectItems = new SelectList(ViewBag.type);
}
<h2>新增文章</h2>
@using (Html.BeginForm("Create", "ACTICLEs", FormMethod.Post, htmlAttributes: new { id = "CreateForm" }))
{
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(false, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.type, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@*@Html.EditorFor(model => model.type, new { htmlAttributes = new { @class = "form-control", pattern = "^.{1,10}$", title = "10個字元內", required = "required" } })*@
@Html.DropDownListFor(model => model.type, selectItems, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.type, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.date, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.date, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.date, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.title, new { htmlAttributes = new { @class = "form-control", pattern = "^.{1,30}$", title = "30個字元內", required = "required" } })
@Html.ValidationMessageFor(model => model.title, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.context, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextAreaFor(model => model.context, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.context, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("回後台", "Index")
</div>
@section header{
<script src="http://cdn.ckeditor.com/4.4.6/standard/ckeditor.js"></script>
}
@section scripts{
<script>
var editor = CKEDITOR.replace('context');
$("#CreateForm").submit(function (event) {
event.preventDefault();
var url = '@Url.Action("Create")'
$.post(url,
{
type: $("#type").val(),
date: $("#date").val(),
title: $("#title").val(),
Context: htmlEncode(editor.getData())
})
.done(function (data) {
window.location.href = '@Url.Action("Index")';
});
});
function htmlEncode(value) {
return $('<div/>').text(value).html();
}
</script>
}
三、jqXHR
jqXHR有提供jqXHR.done()、jqXHR.fail()、jqXHR.always()方法讓USER來使用
另外jqXHR.success()、jqXHR().error()、jqXHR.complete()於jQuery 1.8不推薦使用
程式範例:
var jqxhr = $.get("example.php", function () { alert("success"); }) .done(function () { alert("second success"); }) .fail(function () { alert("error"); }) .always(function () { alert("finished"); }); // Perform other work here ... // Set another completion function for the request above jqxhr.always(function () { alert("second finished"); });
四、jQuery.ajax()
由於這設定還蠻繁雜的,請先參考jQuery.ajax()
參考資料:
延伸參考:
推薦書籍:
jQuery cookbook錦囊妙計 / jQuery community experts著 ; Cody Lindley編 ; 法蘭克譯