Here's my jQuery:
var docname = $('#doc').val();
function parseXml(xml)
{
$(xml).find("rsp").each(function()
{
alert("success");
});
}
$('#submit').click(function() {
$.ajax({
type: "GET",
url: "img_upload.php",
data: "doc=" + docname,
dataType: "xml",
success: parseXml
});
return false;
});
Note that #doc is the id of a form text input box and #submit is the submit button's id. If successful, I'd like a simple "success" javascript popup to appear.
Here's img_upload.php with my API key omitted:
<?php
$filename = $_GET["doc"];
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
// $data is file data
$pvars = array('image' => base64_encode($data), 'key' => <MY API KEY>);
$timeout = 30;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://imgur.com/api/upload.xml');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pvar开发者_StackOverflows);
$xml = curl_exec($curl);
curl_close ($curl);
?>
When directly accessed with a GET argument for "doc", img_upload.php file returns the following XML format:
<?xml version="1.0" encoding="utf-8"?>
<rsp stat="ok">
<image_hash>cxmHM</image_hash>
<delete_hash>NNy6VNpiAA</delete_hash>
<original_image>http://imgur.com/cxmHM.png</original_image>
<large_thumbnail>http://imgur.com/cxmHMl.png</large_thumbnail>
<small_thumbnail>http://imgur.com/cxmHMs.png</small_thumbnail>
<imgur_page>http://imgur.com/cxmHM</imgur_page>
<delete_page>http://imgur.com/delete/NNy6VNpiAA</delete_page>
</rsp>
What's the problem here? Here's the Imgur API page for reference.
var docname = $('#doc').val();
Exactly where is this in your code and when will it be evaluated?
My guess is that it's executed either when the <script> tag has been parsed or you've wrapped it in a $(document).ready() handler. Either way it get's evaluated before the user has actually typed something into the input/text control and docname
will therefore be '' or even null all the time. You want the script to fetch the value not until the user has pressed the submit button.
Try it with
$('#submit').click(function() {
$.ajax({
type: "GET",
url: "img_upload.php",
data: "doc=" + $('#doc').val(),
dataType: "xml",
success: parseXml
});
return false;
});
edit: Even better, make the data property an object and let jquery handle the escaping of the value.
data: {doc: $('#doc').val()}
It could be that you have not set the header in the php script - this should be your first line.
header('Content-Type: text/xml');
精彩评论