可以做一个ajax get然后将那些数据发布到php文件?

时间:2015-10-12 00:54:25

标签: javascript php jquery ajax wordpress

当我在我的表单上单击一个按钮并且我想使用返回的数据构建"结果"我尝试向程序外的控制器发出ajax GET请求。动态地使用PHP / HTML。

我使用以下ajax(请原谅奇怪的jquery格式。由于wordpress'没有冲突模式,我必须使用jQuery()而不是$()。

var $j = jQuery;
$j(document).ready(function(){
$j('.button-1').click(function(){

    var distanceInput = $j('#distance-value').text().match(/[0-9]+/);
    var zipInput = $j('.location-search input').val();

    $j.ajax({
        headers: {
            'Secret' : 'secretkeyexample'
        },
        url: 'https://example.net/api/1/index.php?r=OfficeLocator/getOfficesInRange',
        data: { zip: zipInput , range: distanceInput },
        method: 'GET',
        dataType: 'json',
        success: doSomethingHere
        }
    });

})
});

我想在像这样的PHP文件设置中使用该数据

<div class="fusion-column-wrapper" style="min-height:706px; height:auto">
<?php
    $results; // Store the json data here
    $i = 0;
?>
<h2 data-fontsize="35" data-lineheight="40">Search Results</h2>
<?php foreach ($results as $officeId => $officeArray) : ?>
    <?php $i++ ?>

    <div class="search-result-number"><?php echo $i; ?></div>
    <div class="search-result-city"><?php echo $officeArray['officename']; ?></div>
    <div class="clearfix"></div>
    <p>
        <?php echo $officeArray['addr2'] ?><br>
        <?php echo $officeArray['state'] ?><br>
        <?php echo $officeArray['phone'] ?><br>
        <?php echo $officeArray['fax'] ?><br>
    </p>
    <hr class="search-result-hr">

<?php endforeach ?>

请原谅我,因为我不熟悉AJAX,但我想我要做的是将数据从ajax GET发送到PHP文件。这可能吗?如果是这样,怎么样?

1 个答案:

答案 0 :(得分:0)

尝试使用,因为JavaScript变量规则为var k而不是var $k

    var k = jQuery.noConflict();
    k(document).ready(function(){
       k('.button-1').click(function(){
        var distanceInput = k('#distance-value').text().match(/[0-9]+/);
        var zipInput = k('.location-search input').val(); 
        // Ajax Code Here       
        k.ajax({
            dataType: 'json',
            url: 'https://example.net/api/1/index.php?r=OfficeLocator/getOfficesInRange',
            data: { zip: zipInput , range: distanceInput},                
        });  
       // Ajax Response Here
       .done(function( msg ) {
          alert( "Data Saved: " + msg );
        });  
      });
    });

检查语法enter link description hereenter link description here