AJAX functionless
I have just built an AJAX function. Their are no errors with firebut and the correct response is returned but for some reason it will not fill the field value #crap of fill the div html #outdirections.
AJAX ::
function appdirections() {
var start = $('#start').val();
var end = $('#end').val();
var dataString = 'start=' + start + '&end=' + end;
$.ajax({
type: 'POST',
url: 'http://www.golfbrowser.com/courses/wentworth-east/?appdirections',
data: dataString,
beforeSend: function() {
},
dataType:'json',
success: function(data) {
$('#outdirections').html(data.output);
$('#crap').val(data.output);
},
error: function(data) {
},
});
}
PHP ::
<?php
$start = $_POST['start'];
$end = $_POST['end'];
$xml = simplexml_load_file('http://maps.googleapis.com/maps/api/directions/xml?origin='.$start.'&destination='.$end.'&sensor=false');
// data to fetch
$start = $xml->xpath("/DirectionsResponse/route/leg/start_address");
$end = $xml->xpath("/DirectionsResponse/route/leg/end_address");
// output
echo json_encode( arr开发者_如何学Pythonay('output'=>$start));
?>
HTML
<input type="text" id="crap" value=""/>
<div id="outdirections"></div>
<input id="start" type="text" spellcheck="false" placeholder="enter your post code" onkeypress="if (event.keyCode == 13) {appdirections();}"/>
<input id="end" type="text" value="wentworth virginia water" disabled="disabled"/>
Here is the response from Firebug
{"output":[{"0":"Winkfield, Windsor, Berkshire SL4 2ES, UK"}],"end":[{"0":"Wentworth, Surrey GU25 4, UK"}]}
Most likely you don't have anything in the data.output
Try this and see what it outputs
$('#outdirections').html(data);
$('#crap').val(data);
Im guessing #crap is an input field?
EDIT
anyways, try this alert(data.output[0].get("0"))
or if you simplified you could do this:
alert(data.output[0])
<input id="#start" onkeypress="if (event.keyCode == 13) {appdirections();}" />
implies this code only works for event.keyCode == 13
condition.......This is enter key and an input element will not hold the value of enter key like a/b/c (I think so). For this, when you are pressing enter and calling appdirections()
function $('#start').val()
is null hence the code is not working...
Place the input fields inside a <form>
tag and call the ajax function on submit.
Are you sure you are getting the data correct? Try to place an alert inside success and test if it works.
Look at the manual page for SimpleXMLElement::xpath
:
public array SimpleXMLElement::xpath ( string $path )
This method returns an array of values matched by the XPath query. You are then encoding the array with json_encode
and, surprise surprise, it turns it into a JSON array.
You have two options. You can either get the element of the array with PHP or with Javascript. It's easier to do it with PHP, I think, and will save a few bytes!
echo json_encode( array('output'=>$start[0]));
精彩评论