2018年2月2日 星期五

PHP的測試 (6) ajax 比較

不使用 jQuery時

var updateparent=null;  //the caller change function
var ch_sn=0;            //content id
var isIE = false;       
// global request and XML document objects
var req;
// retrieve XML document (reusable generic function);
// parameter is URL string (relative or complete) to
// an .xml file whose Content-Type is a valid XML
// type, such as text/xml; XML source must be from
// same domain as HTML file
function loadXMLDoc(url, process_fn) {
// branch for native XMLHttpRequest object
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = process_fn;
req.open("GET", url, true);
req.send(null);
// branch for IE/Windows ActiveX version
} else if (window.ActiveXObject) {
isIE = true;
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = process_fn;
req.open("GET", url, true);
req.send();
}
}
}

// This function is used to extract XML data from the returned AJAX string (in XML format)
function getElementTextNS(prefix, local, parentElem, index) {
    var result = "";
    if (prefix && isIE) {
        // IE/Windows way of handling namespaces
        result = parentElem.getElementsByTagName(prefix + ":" + local)[index];
    } else {
        result = parentElem.getElementsByTagName(local)[index];
    }
    if (result) {
        // get text, accounting for possible
        // whitespace (carriage return) text nodes
        if (result.childNodes.length > 1) {
            return result.childNodes[1].nodeValue;
        } else {
            return result.firstChild.nodeValue;   
        }
    } else {
        return "n/a";
    }
}


function processChange()
{
  // only if req shows "loaded"
  if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
  div = document.getElementById('score_'+ch_sn);
div.innerHTML = "";
div.innerHTML = req.responseText;
if(updateparent!=null) { updateparent(); }
updateparent=null;
} else {
alert("There was a problem retrieving the XML data:\n" +
req.statusText);
  }
}
}


function ajaxshow(phpfunc,sn,callback)
{
  //alert('hi');
  var val=phpfunc+sn; //
  //score =
  updateparent=callback;
 
changed=false;
ch_sn=sn;
div1 = document.getElementById('score_'+sn);
div1.innerHTML = "Loaded...";
        loadXMLDoc(val, processChange);
}


使用方式
<a href='#' onClick='a=function ajaxtest(filename,cid) {


改用jQuery

 $.ajax({
    url: filename,
    type: 'GET',
    dataType: 'html',
    beforeSend: function() {
      $('#'+cid).html('Loading...');
    },
    success: function(data) {
      $('#'+cid).html(data);
    }
  });
}

function test1() {
  ajaxtest('test_22ajaxcall.php','yx_1_1');
}

function test2() {
  ajaxtest('test_22ajaxcall.php','yx_2_1');
}prompt(\"分數要改成\");ajaxshow(\"setscore.php?score=\"+a+\"&id=\",\"{$id}\");'>


<input type="button" id='yx_1_3' value="AjaxTest1" onclick='test1();'>
<input type="button" id='yx_2_3' value="AjaxTest2" onclick='test2();'>

沒有留言:

張貼留言