从php文件中获取数据并使用javascript打印所选数据

时间:2014-11-12 01:39:26

标签: javascript php ajax mysqli

我的html页面中有2个div。使用AJAX,JavaScript,我将查询参数发送到php文件,该文件返回2个div的组合结果。我想知道如何在JavaScript中分离结果并在各自的div中显示。

<script>
function fetchData() {
  var yr = document.getElementById('entry').value;
  if (yr.length==0) { 
    document.getElementById("result1").innerHTML="";
    document.getElementById("result2").innerHTML="";
	return;
  }

  var xmlhttp=new XMLHttpRequest();
  xmlhttp.onreadystatechange=function() 
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) 
	 {
		var content = xmlhttp.responseText;
	if (content == "%<searchword>%")
		document.getElementById("result1").innerHTML = content;
	else		
		document.getElementById("result2").innerHTML = content;	
     }
  }
  xmlhttp.open("GET","db.php?q="+ yr ,true);
  xmlhttp.send(); 
}
</script>
<body>

<form>
Enter year: <input type="text" id="entry" />
<input type="button" value="check here" onclick="fetchData()" />
</form>
<div id="result1">result 1 here</div>
<div id="result2"> result 2 here</div>
</body>

1 个答案:

答案 0 :(得分:1)

将json作为PHP输出返回,这对Javascript最好(不要忘记json php头文件,使用json_encode),如下所示:

{
    "div1": "Content for div 1",
    "div2": "DIV 2 content"
}

轻松使用jQuery getJSON method或jQuery $.ajax

$.ajax({
    dataType: "json",
    url: urlToPHPFile,
    data: dataToSend,
    success: function( jsonResponse ) {
        $('#result1').html( jsonResponse.div1 );
        $('#result2').html( jsonResponse.div2 );
    }
});

要使用纯Javascript发送请求,请查看this article

仅解析JSON read this article

所以,使用纯Javascript,你会得到类似的结果:

function alertContents(httpRequest){
    if (httpRequest.readyState == 4){
        // everything is good, the response is received
        if ((httpRequest.status == 200) || (httpRequest.status == 0)){
            var obj = JSON.parse(httpRequest.responseText);
            var div1 = getElementById('result1');
            var div2 = getElementById('result2');
            div1.innerHTML = obj.div1;
            div2.innerHTML = obj.div2;
        }else{
            alert('There was a problem with the request. ' + httpRequest.status + httpRequest.responseText);
        }
    }
};

function send_with_ajax( the_url ){
    var httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function() { alertContents(httpRequest); };  
    httpRequest.open("GET", the_url, true);
    httpRequest.send(null);
};

function fetchData() {
    var yr = document.getElementById('entry').value;
    if (yr.length == 0) {
        document.getElementById("result1").innerHTML = "";
        document.getElementById("result2").innerHTML = "";
        return;
    }
    send_with_ajax( "db.php?q=" + yr );
};

fetchData();