render data without a page load when user clicks on controls

时间:2016-07-21 00:43:41

标签: php jquery ajax

In an application that uses PHP server-side code the following array exists in a file called data.php:

$htdocs = 'C:\xampp\htdocs';
$projects = ['Pies' => [
	'app' => $htdocs. '\PiesAreSquare\OOP',
	'db' => 'C:\MySQL\Scripts'
	],
'Cats' => [
	'app' => $htdocs . '\CatJetInc',
	'db' => 'C:\SQLServer\Scripts'
	]
];

The corresponding web page looks like this: enter image description here

网页上的项目选择框使用$ projects数组中的数组键填充。

我想设置一些内容,以便嵌套数组中的正确文本出现在"路径旁边:"标签。该页面默认为数组中的第一个项目," app"作为脚本类型,所以当页面首先呈现"路径旁边的值时:"在这个例子中,将是$ projects [' Pies'] [' app']中的内容。如果用户选择Cats作为项目,并选择db作为脚本类型,那么应该出现在" path:"旁边的文本。将是$ projects [' Cats'] [' db']的价值。 "路径旁边的值:"每当用户更改"项目中的值时,都应该更改:"框或点击"脚本类型:"单选按钮。我的目标是在不重新加载页面的情况下实现此目的。这怎么可能?

1 个答案:

答案 0 :(得分:0)

这是使用AJAX实现的。可以使用纯JavaScript,尽管我的最终解决方案最终使用jQuery,因为代码更简洁。

页面的HTML如下所示:



<!DOCTYPE HTML>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
		<script src="js/functions.js"></script>		
	</head>
<body>	
<ol>
	<li>
		<label>project:</label>
		<select id="ProjectName" onchange="choosePath()">
			<?php echo $project_options; ?>
		</select>
	</li>
	<li>
		<label>script type:</label>
			<input type="radio" name="ScriptType" onclick="choosePath()" id="app" value="app"/><label for="app" class="rblabel">app</label>
			<input type="radio" name="ScriptType" onclick="choosePath()" id="db" value="db"/><label for="db" class="rblabel">db</label>
	</li>
		<li>
		<label>path:</label>
		<span id="path"></span>
	</li>
  </ol>
  <noscript><br><div class="msg">This site requires the use of JavaScript.  Either enable JS to run or view this site on a browser with JS capability.</div></noscript>
</body>
</html>
&#13;
&#13;
&#13;

在functions.js文件中的jQuery看起来像这样:

&#13;
&#13;
function choosePath()
{
  	$.ajax({
	method: "POST",
	url: "utility/utility1.php",
	data:
	{		
		caller: 'choosePath',
		projectname: $('#ProjectName option:selected').text(),
		scripttype: $('input:radio[name="ScriptType"]:checked').val()
	},
	async: true,
	success:			
	function(data){
		var extracted = JSON.parse(data);
		document.getElementById("path").textContent = extracted.path;		
	}});	
}
&#13;
&#13;
&#13;

实用程序1.php文件中的PHP如下所示:

&#13;
&#13;
<?php
function retrieveParameterValue($key, $default)
{
	return (isset($_POST[$key])) ? $_POST[$key] : $default;
}

require_once ('../includes/data.php');	# make $projects array accessible to this script

$projectname = retrieveParameterValue('projectname', 'default project');
$scripttype = retrieveParameterValue('scripttype', 'default script type');

$path = $projects[$projectname][$scripttype];

$array = ['path' => $path];
	
echo json_encode($array);
?>
&#13;
&#13;
&#13; 结果如下: enter image description here

enter image description here

enter image description here

enter image description here

相关问题