简体   繁体   English

jQuery AJAX发布和刷新页面内容,无需重新加载页面

[英]JQuery AJAX Post and Refresh Page Content without reload page

Now I know that I am at risk here of asking a duplicate question, however I don't really know what to search for because I am a complete AJAX jQuery noob. 现在,我知道我在这里要问一个重复的问题,但是我真的不知道要搜索什么,因为我是一个完整的AJAX jQuery noob。 Believe me, I have tried searching what I think is the obvious, with no luck so please go easy on me. 相信我,我尝试搜索我认为很明显的东西,但是没有运气,所以请放轻松。

I have a php wordpress site which shows prices in GBP as default. 我有一个PHP wordpress网站,默认显示的价格为GBP。 At the top, is a select box with onchange="this.form.submit()" which allows the user to change the default currency that all prices are quoted in. 顶部是带有onchange="this.form.submit()"的选择框,它使用户可以更改所有报价所用的默认货币。

<form method="post" action="">
    <select name="ChangeCurrency" onChange="this.form.submit()">
        <option value="GBP">GBP</option>
        <option value="USD">USD</option>
        <option value="EUR">EUR</option>
    </select>
</form>

On the home page, are several, what I call "shortcode widgets" , each one containing products and price tables. 在主页上,有几个我称为“短代码小部件”的小部件 ,每个小部件都包含产品和价格表。 A dashboard if you like. 仪表板,如果您喜欢。

How it currently works (inefficient): 当前工作方式(低效):

  1. User changes select. 用户更改选择。
  2. Form submitted 表格已提交
  3. Homepage reloaded with updated prices in selected currency. 重新加载首页,并以选定的货币显示更新的价格。

This is not good, because whenever somebody changes currency, the whole page is reloaded (this takes time, transfers approx 1mb without caching, not to mention unnecessary load on the server). 这不好,因为每当有人更改货币时,整个页面都将重新加载(这需要时间,在不进行缓存的情况下传输大约1mb的内存,更不用说服务器上的不必要负载了)。

What I want (more efficient): 我想要的(效率更高):

  1. When the select box is changed, I wish to asynchronously post the form which changes the currency session variable. 当选择框更改时,我希望异步发布更改货币会话变量的表格。
  2. Each "shortcode widget" is updated one by one without having to reload the entire page. 每个“简码小部件”都被一个一个地更新,而不必重新加载整个页面。

Is this something that jquery can do? jQuery可以做到这一点吗? where do I start? 我从哪里开始?

Just in case it makes any difference so that you can see what I mean, here is the URL so that you can see what I am talking about... http://bit.ly/10ChZys 以防万一它有所不同,以便您可以理解我的意思,这里是URL,以便您可以了解我在说什么... http://bit.ly/10ChZys

PART 2: I have used jQuery and ajax to update the fixTable thanks to a mashup of answers below... I am using session variables to store the users choice, that way, if they return to the site, the option will be saved. 第2部分:由于使用了以下答案,我使用jQuery和Ajax更新了FixTable ...我使用会话变量来存储用户的选择,这样,如果他们返回站点,则该选项将被保存。

I am having problems with my code because the session variable stored within http://goldealers.co.uk/wp-content/plugins/gd/tables.php?currency=GBP&table=fixTable appears to have a different session_id to the user's session id because the option is no longer stored. 我的代码有问题,因为存储在http://goldealers.co.uk/wp-content/plugins/gd/tables.php?currency=GBP&table=fixTable中的会话变量似乎与用户会话具有不同的session_id id,因为该选项不再存储。

Is there a way of telling the server that they are one and the same session? 有没有办法告诉服务器它们是同一会话?

SOLUTION I used Ribot's Solution to start with which worked and solved the initial problem, then extended with NomikOS's solution... 解决方案我从Ribot的解决方案开始就解决了最初的问题,然后扩展了NomikOS的解决方案...

Yes, jQuery can do it using ajax. 是的,jQuery可以使用ajax做到这一点。

First of all, when using ajax, you don't have to post a form to get the data. 首先,在使用ajax时,您无需发布表单即可获取数据。 Ajax in jQuery will load the text data of an url. jQuery中的Ajax将加载网址的文本数据。

You may start by giving your select an id (here id="changeCurrency") and: 您可以先给您的选择一个ID(此处为id =“ changeCurrency”),然后开始:

$("#changeCurrency").change(function(){
    currency = $('#changeCurrency option:selected').val() // get the selected option's value
    $("#some_div").load("someurl.php?currency=" + currency);
});

Now read up on jQuery and ajax for what kind of ajax call you need to do that suites your needs the best. 现在阅读jQuery和ajax,了解需要哪种类型的ajax调用才能满足您的最佳需求。

NOTE: this answer show some ideas about the php backend for the AJAX process. 注意:此答案显示了有关AJAX进程的php后端的一些想法。 It is a complement for the other answers talking about the frontend process. 它是有关前端过程的其他答案的补充。

1.- a mockup to manage AJAX request in WP, just some ideas, ok? 1.-在WP中管理AJAX请求的模型,只是一些想法,好吗?

add_action('init', 'process_ajax_callback');

function process_ajax_callback()
{
    if ( ! $_REQUEST['go_ajax'])
    {
        return;
    }

    try
    {
        if (isset($_REQUEST['nonce_my_ajax']))
        {
            $nonce   = $_REQUEST['nonce_my_ajax'];
            if ( ! wp_verify_nonce($nonce    = $_REQUEST['nonce_my_ajax'], 'nonce_my_ajax'))
            {
                throw new Exception("Nonce token invalid."); // security
            }
        }
    }
    catch (Exception $e)
    {
        $output['result']    = false;
        $output['message']   = $e->getMessage();

        echo json_encode($output);
        exit;
    }

    $result  = true;
    $message = '';

    switch ($_REQUEST['action'])
    {
        case 'update_price':
        try
        {
            // update price
            // price value comes in $_REQUEST['price']
        }
        catch (Exception $e)
        {
            $result              = false;
            $message             = $e->getMessage();
        }
        break;      

        case 'other_actions':
        break;      
    }

    $output['result']    = $result ? true : false;
    $output['message']   = $message;

    echo json_encode($output);
    exit;
}

2.- don't forget security 2.-不要忘记安全

// nonce_my_ajax is passed to javascript like this:
wp_localize_script('my_js_admin', 'myJsVars', array(
    'nonce_my_ajax'  => wp_create_nonce('nonce_my_ajax')
));

3.- in general the needed in the frontend (to use with the backend mockup showed above) is something like: 3.-通常,前端(与上面显示的后端模型一起使用)所需的内容如下:

$("select[name='ChangeCurrency']").live("change", function() {
    var price = $(this).val();
    $.post(
            window.location.href,
            {
                go_ajax : 1, // parse ajax
                action : 'update_price', // what to do
                price : price, // vars to use in backend
                nonce_my_ajax : myJsVars.nonce_my_ajax // security
            },
            function(output) {
            if ( output.result == true )
                // update widgets or whatever
                // $("#my_div").html("we happy, yabadabadoo!");
                // or do nothing (AJAX action was successful)
            else
                alert(output.message)
            }, 'json');
});

4.- You can use $.get() or $.post() to send/process data to/in server but .load() is not good when you update DB because you can't manage returning messages of failures with the precision of a json response (for example: multiples validation error messages). 4.-您可以使用$.get()$.post()向服务器发送数据或在服务器中处理数据,但是.load()在更新数据库时效果不佳,因为您无法使用json响应的精度(例如:倍数验证错误消息)。 Just use .load() to load HTML views. 只需使用.load()即可加载HTML视图。

UPDATE: 更新:

Set session_id() where can be executed both for normal requests and for ajax requests and at the early stage as possible. session_id()设置为可以在普通请求和ajax请求中执行的位置,并且尽可能早地执行。 I hope you are using a class to wrap your plugin, if not now is the right moment to do it... example: 我希望您正在使用一个类来包装您的插件,如果现在还不适合的话,可以这样做...例如:

class my_plugin {

    function __construct()
    {
        if ( ! session_id())
        {
            session_start();
        }

        add_action('init', array($this, 'process_ajax_callback'));

        // ...
    }   

    function process_ajax_callback()
    {
        // ...
    }
}

UPDATE 2: 更新2:

About nonce based security: 关于基于随机数的安全性:

A security feature available in WordPress is a “nonce”. WordPress中可用的安全功能是“ nonce”。 Generally, a “nonce” is a token that can only be used once and are often used to prevent unauthorised people from submitting data on behalf of another person. 通常,“一次性”是一种令牌,只能使用一次,并且通常用于防止未经授权的人员代表他人提交数据。

Ref: http://myatus.com/p/wordpress-caching-and-nonce-lifespan/ 参考: http : //myatus.com/p/wordpress-caching-and-nonce-lifespan/

In this mockup nonce_my_ajax is just an example, indeed it should be more unique like nonce_{my_plugin_name} , or even better nonce_{my_plugin_name}_{what_action} where what_action represents updating user , or inserting new book , etc... 在此模型中, nonce_my_ajax只是一个示例,实际上它应该像nonce_{my_plugin_name}或更独特的nonce_{my_plugin_name}_{what_action}更独特,其中what_action表示updating userinserting new book等。

More info about it: WP Codex: WordPress Nonces , WPtuts+: Capabilities and Nonces . 关于它的更多信息: WP Codex:WordPress NoncesWPtuts +:Capabilities and Nonces

Drop the onchange and add an ID 删除onchange并添加一个ID

<select name="ChangeCurrency" id="ChangeCurrency">...

On the page give all your prices a price in your base currency as well as outputting them 在页面上,以您的基础货币给出所有价格,然后输出

<span class="price" data-base="0.12">&pound;0.12</span>

In your JS have a conversion table 在您的JS中有一个转换表

// base currency is GBP
// each currency has 0: currency symbol, 1: conversion rate
var currency={"GBP":["&pound;", 1], "USD":["&dollar;", 0.67]};
var usercurrency=currency['GBP'];

and bind an event to the change 并将事件绑定到更改

$('#ChangeCurrency').on('change', function(){
    // post to the server to update it
    $.post(...);
    // set locally on the page
    usercurrency=currency[$(this).val()];
    // and change all the values
    $('.price').each(function(){
        $(this).html(usercurrency[0] + (usercurrency[1] * $(this).data('base')).toFixed(2) );
    });
}).trigger('change'); // trigger this to run on page load if you want.

I haven't checked any of this code 我没有检查任何代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM