jQuery Ajax Sample

PHPに値を送信して受け取る[1]

jQuery

$(function() {
  $(document).on('click','#button1',function(){
    $("#form1 p").remove(); //削除
      $.ajax({
            type: "POST",
            url: "ajax1.php",
            data: 'name1='+$("#name1").val(),
            dataType :'html' //html指定
      }).done(function(str){
        $("

").html(str).appendTo("#form1"); //HTMLで表示される $("

").text(str).appendTo("#form1"); //テキストで表示される }).fail(function(str){ $('#form1').append('取得に失敗しました'); }); }); });

ajax1.php


  

PHPに値を送信して受け取る[2]

jQuery

$(function() {
  $(document).on('click','#button2',function(){
    $("#form2 p").remove(); //削除
      $.ajax({
            type: "POST",
            url: "ajax2.php",
            data: 'name2='+$("#name2").val(),
            dataType :'xml' //xml指定
      }).done(function(str){
       // $("

").html(str).appendTo("#form2"); //これはエラーになる $("

").text(str).appendTo("#form2"); //[object XMLDocument] $("

").text( $(str).find("name").text() ).appendTo("#form2"); $("

").text( $(str).find("time").text() ).appendTo("#form2"); }).fail(function(str){ $('#form2').append('取得に失敗しました'); }); }); });

ajax2.php

 header("Content-type: application/xml");
 echo ' ' . "\n";
 ?>