WP Http XML响应HTML编码和图像显示问题

时间:2014-09-09 作者:Richard King

这是我的第一个WP插件。这里可能会有不止一个问题,它们都是相关的,所以我将在这里问所有的问题。

工作测试here

要使用的跟踪编号:lc0614061377

Example XML Response from tracenow.net:

<Consignment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
    <consignmentNumber>lc0614061377</consignmentNumber>
    <customerRef/>
    <itemCount>1</itemCount>
    <name>six red squares</name>
    <address1>unit 7b victoria business park</address1>
    <address2>short street</address2>
    <town>SOUTHEND ON SEA</town>
    <county>ESSEX</county>
    <postcode>ss2 5by</postcode>
    <country>United Kingdom</country>
    <recipient>cannon</recipient>
    <status>Delivered</status>
    <collected>0001-01-01T00:00:00</collected>
    <delivered>2014-07-25T10:00:50</delivered>
    <collectionCode/>
    <deliveryCode>Delivered OK</deliveryCode>
    <comments/>
    <created>2014-07-24T15:00:40</created>
    <deliveryLatitude>51.54617</deliveryLatitude>
    <deliveryLongitude>0.712245</deliveryLongitude>
    <deliverySignature>
        http://resources.tracenow.net/signatures/d5dbffb4-0336-44bf-b72c-00fb9aaac759/0a630170-1390-4ca4-b104-5ca4b9b6199f.jpg
    </deliverySignature>
    <deliveryImage>
        http://resources.tracenow.net/images/d5dbffb4-0336-44bf-b72c-00fb9aaac759/6de6c2bd-236b-447d-a106-b1a7bd537645.jpg
    </deliveryImage>
</Consignment>
这是我的代码的当前状态:

// tracenow.php

<?php
 /*
 Plugin Name: TraceNow Tracking
 Plugin URI: http://www.titandesign.co.uk
 Description: A simple parcel tracking plugin for Codeway TraceNow.
 Version: 4.0
 Author: Richard King
 Author URI: http://www.titandesign.co.uk/
 License: GPL-2.0+
 License URI: http://www.opensource.org/licenses/gpl-license.php 
 */

 wp_enqueue_script( \'my-ajax-handle\', plugin_dir_url( __FILE__ ) . \'ajax.js\', array( \'jquery\' ) );
 wp_enqueue_style( \'my-ajax-handle\', plugin_dir_url( __FILE__ ) . \'style.css\' );
 wp_localize_script( \'my-ajax-handle\', \'the_ajax_script\', array( \'ajaxurl\' => admin_url( \'admin-ajax.php\' ) ) );

 // THE TRACKING FUNCTION
 if( !class_exists( \'WP_Http\' ) )
include_once( ABSPATH . WPINC. \'/class-http.php\' );

 function tracking_function(){ 
 //if ( isset( $_POST[\'consignmentNumber\'] ) && \'1\' == $_POST[\'consignmentNumber\'] ){
    $consignmentNumber = $_POST[\'consignmentNumber\'];
    $url = (\'http://services.tracenow.net/TraceNowAccess.asmx/GetConsignment?consignmentNumber=\' .($consignmentNumber) .\'&externalAccessGuid=d5dbffb4-0336-44bf-b72c-00fb9aaac759\');
    $args = array(
                \'method\' => \'GET\',
                \'timeout\' => 45,
                \'redirection\' => 5,
                \'httpversion\' => \'1.1\',
                \'content-type\' => \'application/x-www-form-urlencoded\',
                \'body\' => array(),
                \'headers\' => array(),
                \'blocking\' => true,
                \'cookies\' => array(),
                \'connection\' => \'close\',
                );

    $response = wp_remote_get( $url, $args );
    if ( is_wp_error( $response ) ) {
            $error_message = $response->get_error_message();
                 echo "Something went wrong: $error_message";
            } else {
                /*include (\'/render_xml_to_html.php\');
                        if(function_exists(\'render_xml_data\')){
                            render_xml_data(\'example_data.xml\');
                            }else{
                            echo null;
                        } */
                    echo \'<h3>Consignment Details</h3>\' . \'<pre>\' . print_r($response[\'body\'], true) . \'</pre>\';// this is passed back to the javascript function
                    die();
            } // end if
    //} // end if               
 }

 // THE AJAX ADD ACTIONS
add_action( \'wp_ajax_the_ajax_hook\', \'tracking_function\' );
add_action( \'wp_ajax_nopriv_the_ajax_hook\', \'tracking_function\' ); // need this to serve non logged in users

// ADD TRACKING FORM TO THE PAGE

function tracenow_frontend(){
$the_form = \'
<form id="theForm" method="POST">
<input id="consignmentNumber" name="consignmentNumber" value="Consignment No" type="text" />
<input name="action" type="hidden" value="the_ajax_hook" /> <!-- this puts the action the_ajax_hook into the serialized form -->
<input id="submit_button" value="Track" type="button" onClick="submit_me();" />
 </form>
 <div id="response_area">
    Your tracking details will appear here
</div>\';// END DIV RESPONSE AREA
return $the_form;
}
 add_shortcode("tn_ajax_frontend", "tracenow_frontend");

// ajax.js
function submit_me(){
        jQuery.post(the_ajax_script.ajaxurl, jQuery(\'#theForm\').serialize()
        ,
        function(response_from_tracking_function){
            jQuery("#response_area").html(response_from_tracking_function);
            }
        );
        jQuery(\'#theForm\').find(\'input[type=text]\').val(\'Consignment No\');      
}

// render_xml_to_html.php
<?php
/*
    Written by Gary Hollands Sept 2010
    This work is available under the terms of the GNU General Public License, http://www.gnu.org/licenses/gpl.html
    render_xml_data is a function that can use XML data and present that data as HTML.
*/
function render_xml_data($path_to_xml_file){
    if (!file_exists($path_to_xml_file)){
        return;
    }else{
        $chars_to_replace = array(\'[\\r]\',\'[\\n]\',\'[\\t]\');
        $xmlstring = trim(preg_replace($chars_to_replace, \'\', file_get_contents($path_to_xml_file)));
    }
    $xml = new SimpleXMLElement($xmlstring);
    foreach ($xml->consignment as $consign) {
            echo \'<div class="consignment">\'."\\n";
            echo \'<h3>\'.$consign->consignmentnumber.\'</h3>\'."\\n";
            echo \'<p><span class="category">Customer Ref: </span>\'.$consign->customerref.\'</p>\'."\\n";
            echo \'<p><span class="category">Number of items: </span>\'.$consign->itemcount.\'</p>\'."\\n";
            echo \'<p><span class="category">Name: </span>\'.$consign->name.\'</p>\'."\\n";
            echo \'<p><span class="category">Address 1: </span>\'.$consign->address1.\'</p>\'."\\n";
            echo \'<p><span class="category">Address 2: </span>\'.$consign->address2.\'</p>\'."\\n";
            echo \'<p><span class="category">Town: </span>\'.$consign->town.\'</p>\'."\\n";
            echo \'<p><span class="category">County: </span>\'.$consign->county.\'</p>\'."\\n";
            echo \'<p><span class="category">Postcode: </span>\'.$consign->postcode.\'</p>\'."\\n";
            echo \'<p><span class="category">Country: </span>\'.$consign->country.\'</p>\'."\\n";
            echo \'<p><span class="category">Recipient: </span>\'.$consign->recipient.\'</p>\'."\\n";
            echo \'<p><span class="category">Status: </span>\'.$consign->status.\'</p>\'."\\n";
            echo \'<p><span class="category">Collected: </span>\'.$consign->collected.\'</p>\'."\\n";
            echo \'<p><span class="category">Delivered: </span>\'.$consign->delivered.\'</p>\'."\\n";
            echo \'<p><span class="category">Collection Code: </span>\'.$consign->collectioncode.\'</p>\'."\\n";
            echo \'<p><span class="category">Delivery Code: </span>\'.$consign->deliverycode.\'</p>\'."\\n";
            echo \'<p><span class="category">Comments: </span>\'.$consign->comments.\'</p>\'."\\n";
            echo \'<p><span class="category">Created: </span>\'.$consign->created.\'</p>\'."\\n";
            echo \'<p><span class="category">Delivery Latitude: </span>\'.$consign->deliverylatitude.\'</p>\'."\\n";
            echo \'<p><span class="category">Delivery Longitude: </span>\'.$consign->deliverylongitude.\'</p>\'."\\n";
            echo \'<p><span class="category">Delivery Signature: </span><img src="/\'.$consign->deliverysignature.\'/"/></p>\'."\\n";
            echo \'<p><span class="category">Delivery Image: </span><img src="/\'.$consign->deliveryimage.\'/"/></p>\'."\\n";
            echo \'</div><!--end consignment-->\'."\\n";
    }
}

Link to GitHub Gist

所以开始吧。跟踪功能正在工作,并返回来自服务器的响应。

如何将响应呈现为HTML以显示在页面上。目前,它正在返回请求的XML正文,这正是我所需要的。我需要以不为空的节点为目标,并用标题返回它们。我想添加标题的寄售编号示例\'Consignment No:\'. 同样适用于address, status, time, GeoLoc 等等,我考虑过使用jQuery和CSS:before来添加标题。我还有一个render_xml_to_html.php 我假设该文件是正确的方法,但实现时得到的唯一返回值是0。有什么建议吗img, src=""alt="" 标记,以便将图像链接显示为图像。请帮忙addpage, 每次都会创建一个新页面。原因:我希望能够将插件添加为小部件

1 个回复
最合适的回答,由SO网友:kaiser 整理而成

WordPress使用依赖API注册依赖项。它相当简单:注册&;将脚本排队,然后使用wp_localize_script(), 其中添加了<script> 包含DOM数组的标记(正好在脚本添加到DOM之前):

add_action( \'wp_enqueue_scripts\', function()
{
    $name = \'handle\';
    wp_register_script(
        $name,
        plugins_url( \'assets/ajax.js\', __FILE__ ),
        [ \'jquery\' ],
        filemtime( plugins_dir_path( __FILE__ ).\'assets/ajax.js\' ),
        true
    );
    wp_enqueue_script( $name );
    wp_localize_script(
        $name,
        "{$name}Obj", // This string is what gives you access to below array
        [
            \'ajaxurl\'     => esc_url( admin_url( \'admin-ajax.php\' ) ),
            \'_ajax_nonce\' => wp_create_nonce( "{$name}_action" ),
            \'action\'      => "{$name}_action",
            \'data\'        => [ /* additional data as array */ ],
        ]
    );
} );
你可能会注意到,我wp_create_nonce() 并出于安全原因(验证回调中请求的来源)向调用传递了一个action属性。

如何执行远程请求并获取XML数据当从远程请求加载数据时,应使用WP HTTP API, 但具有更高级别的功能。

示例插件,将执行请求并将结果添加到页脚下方(包括管理员和前端):

<?php
/** Plugin Name: (#160775) Fetch XML from TraceNow.net - Part 1 */

add_action( \'shutdown\', function()
{
    $request  = wp_remote_get( 
        \'http://services.tracenow.net/TraceNowAccess.asmx/GetConsignment?\'.
        join( \'&\', [
            \'consignmentNumber\'  => \'lc0614061377\',
            \'externalAccessGuid\' => \'d5dbffb4-0336-44bf-b72c-00fb9aaac759\'
        ],
    );
    $response = wp_remote_retrieve_body( $request, [
        // *additional args
    ] );

    is_wp_error( $response )
        AND wp_send_json_error( $response->get_error_code() ); 

    if ( 
        \'OK\' !== wp_remote_retrieve_response_message( $response )
        OR 200 !== wp_remote_retrieve_response_code( $response )
    )
        wp_send_json_error( $response );

    var_dump( wp_send_json_success( $response ) );
} );
这是执行此类请求的最简单方法。如您所见,我使用的是JSON。XML从WPs HTTP API中消失了,因为JSON的某些版本更易于使用。

提示:wp_remote_*() 接受第二个参数,即can read about on Code.

无论AJAX是否已初始化,都要执行操作(请参见 要了解更多信息),您需要一个表单。

<form id="asktracenow">
    <input name="consignmentNumber" />
    <input name="submit" value="submit" />
</form>
现在,此表单已提交$_POST 在URl中使用数据之前,您需要对其进行清理。根据数据的构造方式,您有多个选项。首先我们只是$cnum = trim( $_POST[\'consignmentNumber\'] ), 然后我们进行验证,以防对其进行清理。

if ( false !== filter_var( $cnum, FILTER_VALIDATE_INT ) )
{
    // do stuff with your absolute, positive integer
    // adjust the check to only pass valid data
}
确保你在这件事上增加了很多分量——你永远不知道你会得到什么回报。

Ajaxing things只需将东西挂接到WP操作上。综上所述,这将密切关注以下内容。

// Public or private?
add_action( \'wp_ajax_handle_action\', function( $data )
{
    check_ajax_referer( $data[\'action\'] );

    # @TODO sanitize data here:
    // filter_var() filter_var_array() and filter_input()
    # @TODO Custom logic here

    // Error?
    if ( is_wp_error( $thing ) )
        wp_send_json_error( $data );

    // Success!
    wp_send_json_success( $data );
} );
提示:将所有这些放在一个单独的插件中,以分离关注点和可移植性。

JavaScript AJAX/请求处理

为了让这个答案更完整,下面是a link to another answer by me 这详细解释了这一点huge example Gist 附件。

结束

相关推荐

未发生jQuery的AJAX请求

我的问题是:无法使用jQuery执行POST请求。下面是完整的描述:我在页面中创建了一个链接(使用帖子和页面的插件PHP代码):<?php $nonce = wp_create_nonce(\"test_nonce\"); $link = admin_url(\'admin-ajax.php?action=my_delete_object&object_id=\'.$object_id.\'&nonce=\'.$nonce);