我有以下 index.html:
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<title>galshan ajax</title>
<script>
$(document).ready(function(){
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "add.php",
action: "get_prof",
data: { "par" : '' },
dataType: "json",
async: true,
success: function(data) {
var select = $('#mySelect');
$(data).find('root').each(function(){
$(this).find('p').each(function(){
var textVal = $(this).val('n');
var valueVal = $(this).val('i');
select.append("<option class='ddindent' value='"+ valueVal +"'>"+textVal+"</option>");
});
});
select.children(":first").text("pick one").attr("selected",true);
} //sucess close
});
});
</script>
</head>
<body>
<div id="page-wrap">
<select id="mySelect">
<option>loading</option>
</select>
</div>
</body>
</html>
add.php 文件是:
<?php
function get_prof(){
$par = isset($_POST['par'])?$_POST['par']:'';
// where are we posting to?
$url = 'example.com/GetProf';
// what post fields?
$logins = array(
'clientID' => 'idnum',
'username' => 'name',
'password' => 'password',
'par' => $par
);
// build the urlencoded data
$postvars = http_build_query($logins);
// open connection
$curl_handle = curl_init();
// set the url, number of POST vars, POST data
curl_setopt($curl_handle, CURLOPT_URL, $url);
curl_setopt($curl_handle, CURLOPT_POST, count($logins));
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $postvars);
// execute post
$result = curl_exec($curl_handle);
// close connection
curl_close($curl_handle);
}
?>
响应如下:
<?xml version="1.0" encoding="utf-8"?>
<root>
<p i="9107" n="content01" />
<p i="9267" n="content02" />
<p i="9106" n="content03" />
<p i="9078" n="content04" />
<p i="9282" n="content05" />
<p i="1000" n="content06" />
<p i="1200" n="content07" />
<p i="9097" n="content08" />
<p i="1400" n="content09" />
<p i="9242" n="content10" />
</root>
我基本上是在尝试使用文本是 n 值而实际值是 i 的选项填充#mySelect。我有几个问题:
- 我似乎无法从 ajax 脚本调用 add.php 文件中的函数,如果我没有在 php 文件中声明该函数,我会得到响应,但我似乎无法返回它。我需要做什么才能从 ajax 脚本调用 php 文件中的特定函数?
- 当我从外部网站获得响应时,我似乎无法将数据作为选项附加到选择元素中,我做错了什么?
这个项目需要在本周结束,如果有人能帮助我,我将不胜感激。