Php AJAX值错误(有时)

Php AJAX值错误(有时),php,ajax,Php,Ajax,我对一段Ajax代码有一个问题,我对Ajax不太熟悉。其他人编写了Ajax代码,该代码可以工作,也可以不工作: <?php include('includes/db_connection.php'); include('includes/sessions.php'); include('includes/functions.php'); include('includes/header.php'); include('includes/navbar-logged.php'); requi

我对一段Ajax代码有一个问题,我对Ajax不太熟悉。其他人编写了Ajax代码,该代码可以工作,也可以不工作:

<?php

include('includes/db_connection.php');
include('includes/sessions.php');
include('includes/functions.php');
include('includes/header.php');
include('includes/navbar-logged.php');
require_once('api-sape.php');
// init sape
$sape        = new SapeApi();
$userId      = $sape->login(SAPE_USER, SAPE_PASS);  
// isset
$siteId = isset($_GET['id']) ? (int)$_GET['id'] : null;
// query this offers details
$siteRow = DB::getInstance()->selectOneByField('sites', 'site_id', $siteId);
// get the logged in users id
$r = get_logged_in_users_details($member);
// the ID
$hID = $r['member_id'];
// paid?
if ($user['member_fees_paid'] == 0){
    stderr('Only subscribed users can buy links! you can <a href="my-account.php">subscribe on your control panel page</a> by clicking the paypal button.');
}
?>
<?php
if (isset($_POST['submitPurchase'])) {
    if ($member == SAPE_USER) { showPre($_POST); }
    // try...
    try {
      // vars
      $pageID     = $_POST['page_id'];
      $urlID      = $_POST['url_id'];
      $memberID   = $_POST['member_id']; 
      $anchorText = $_POST['anchor_text']; 
      $anchorID   = $_POST['anchor_id']; 
      $projID     = $_POST['project_id']; 
      $linkPrice  = $_POST['price'];    
      // buy the link in sape (only if you are admin do they go direct :))
      if ($member == SAPE_USER) { $userBuy = $sape->placement_create($pageID, $urlID, $anchorText); }
      // show var_dump
      if ($member == SAPE_USER) { showPre($userBuy); }
      // insertion (the user still needs to pay first before they go live)
      DB::getInstance()->insert(
            'pending',
        [
            'pending_page_id' => $pageID,
            'pending_url_id' => $urlID,
            'pending_member_id' => $memberID,
            'pending_project_id' => $projID,
            'pending_anchor_id' => $anchorID,
            'pending_text' => $anchorText,
            'pending_price' => $linkPrice,
            'pending_added' => date('Y-m-d H:i:s')
      ]);   
      if ($member == SAPE_USER) {
          // insertion
          DB::getInstance()->insert(
                'purchased',
            [
                'purchased_sape_ref_id' => $userBuy,
                'purchased_member_id' => $memberID,
                'purchased_project_id' => $projID,
                'purchased_anchor_id' => $anchorID,
                'purchased_text' => $anchorText,
                'purchased_price' => $linkPrice,
                'purchased_added' => date('Y-m-d H:i:s')
          ]); 
      }  
      // message      
      stdmsg('Link is queued to go live, checkout on the <a href="links-pending.php">links pending purchase</a> screen.');  
    } catch (SapeApiException $e) {
            stderr($e->getMessage());
    } 
}
?>
<div class="panel panel-primary">
    <div class="panel-heading">URL: <a href="<?php echo $siteRow['site_sape_url']; ?><?php echo $siteRow['site_uri']; ?>" target="_blank"><b><font color="yellow"><?php echo $siteRow['site_sape_url']; ?><?php echo $siteRow['site_uri']; ?></font></b></a></div>
    <div class="panel-body">
    <?php
    $conversion = currencyConverter("RUB", "USD", $siteRow['site_uri_price']);
    ?>
        <form action="" method="post" class="form-horizontal container-fluid" role="form">  
        <table class="table table-condensed table-striped table-hover table-responsive">
            <thead>
            <tr>
                <th>URL ID</th>
                <th>Page ID</th>
                <th>Site Level</th>
                <th>Cost (₽ in Rubles)</th>
                <th>Cost ($ in Dollars)</th>
            </tr>
            </thead>
            <tbody>
             <tr>
                <td><?php echo $siteRow['site_sape_id']; ?></td>
                <td><?php echo $siteRow['site_uri_id']; ?></td>
                <td><?php echo $siteRow['site_level']; ?></td>
                <td><?php echo "₽".$siteRow['site_uri_price']; ?></td>
                <td><?php echo "$".number_format($conversion, 2); ?></td>
             </tr>
            </tbody>
        </table>
        </div>
        <div class="panel-footer">
        <b>Choose a Project:</b><select id="projects" name="project_id" class="form-control" required="required">       
        <?php
            $oneRows = DB::getInstance()->select('SELECT * FROM `projects` WHERE `project_member_id`='.$hID);   
        ?>  
        <?php foreach ($oneRows as $ro1) { ?>
        <option id="<?php echo htmlspecialchars($ro1['project_sape_link_id']) ?>" value="<?php echo htmlspecialchars($ro1['project_sape_id']) ?>"><?php echo htmlspecialchars($ro1['project_name']) ?></option>
        <?php } ?>      
        </select>
        <?php
        // query sape...
        $links = $sape->get_url_anchors($oneRows[0]['project_sape_link_id']);   
        ?>
        <b>Choose the Text that will be posted on the target URL:</b><select id="anchors" name="anchor_id" class="form-control" required="required">
        <?php foreach ($links as $link) { ?>
        <option value="<?php echo htmlspecialchars($link["id"]) ?>"><?php echo htmlspecialchars($link["anchor"]) ?></option>
        <?php } ?>
        <?php
        // page_id is the page or uri of the url/pahe.html etc
        // project_sape_link_id is the id of the site we add in create a project screen.
        ?>
        <input type="hidden" id="url_id" name="url_id" value="<?php echo $oneRows[0]['project_sape_link_id']; ?>" />
        <input type="hidden" id="anchor_text" name="anchor_text" value="<?php echo $links[0]["anchor"]; ?>" />
        </select>
        <br />
        <button type="submit" name="submitPurchase" class="btn btn-default">Buy Link</button>
        <input type="hidden" name="member_id" value="<?php echo $hID; ?>" />
        <input type="hidden" name="page_id" value="<?php echo $siteRow['site_uri_id']; ?>" />
        <input type="hidden" name="price" value="<?php echo $siteRow['site_uri_price']; ?>" />
        </div>
    </div>
    <script>
        jQuery("#projects").on('change',function(){
            var link_id = jQuery("#projects option:selected").attr('id');   
            $("#url_id").val(link_id);
            jQuery.post("ajax-get-anchors.php",{
                linkID:link_id
            }).done(function( data ) {
                $("#anchors").empty();
                var result = jQuery.parseJSON(data);
                for(var i = 0; i < result.length;i++){
                    $("#anchors").append('<option id="'+result[i].id+'">'+result[i].anchor+'</option>');
                }
                $("#anchor_text").val(result[0].anchor);
            });
        });
        jQuery("#anchors").on('change',function(){
            var anchor = jQuery("#anchors option:selected").text();
            $("#anchor_text").val(anchor);
        });     
    </script>
  </form>
</div>
<?php

include('includes/footer.php');
示例正确:

array(8) {
  ["project_id"]=>
  string(7) "2597941"
  ["anchor_id"]=>
  string(10) "2501662973"
  ["url_id"]=>
  string(9) "100717187"
  ["anchor_text"]=>
  string(58) "Create a project, you can use the macro #a#project1#/a# in"
  ["submitPurchase"]=>
  string(0) ""
  ["member_id"]=>
  string(1) "1"
  ["page_id"]=>
  string(10) "1252888864"
  ["price"]=>
  string(4) "0.60"
}
在错误的示例中,锚定id被锚定文本替换,这会把事情搞砸

我希望这是有道理的

此块中缺少value属性。我已经发表了评论并更正了它

   jQuery("#projects").on('change',function(){
        var link_id = jQuery("#projects option:selected").attr('id');   
        $("#url_id").val(link_id);
        jQuery.post("ajax-get-anchors.php",{
            linkID:link_id
        }).done(function( data ) {
            $("#anchors").empty();
            var result = jQuery.parseJSON(data);
            for(var i = 0; i < result.length;i++){
                //Add value attribute here:
                $("#anchors").append('<option id="'+result[i].id+'" value="'+result[i].anchor+'">'+result[i].anchor+'</option>');
            }
            $("#anchor_text").val(result[0].anchor);
        });
    });
同样,同一块的更干净版本将如下所示:

$.each(result, function(key, value) {   
    $('#anchors')
    .append($('<option>', { value : key })
    .text(value)); 
});

上面删除了HTML字符串中转义的所有引号,使其更易于阅读。祝你好运

谢谢你axlj,这里的一些人真是难以置信,他们曾经投过反对票。
   jQuery("#projects").on('change',function(){
        var link_id = jQuery("#projects option:selected").attr('id');   
        $("#url_id").val(link_id);
        jQuery.post("ajax-get-anchors.php",{
            linkID:link_id
        }).done(function( data ) {
            $("#anchors").empty();
            var result = jQuery.parseJSON(data);
            for(var i = 0; i < result.length;i++){
                //Add value attribute here:
                $("#anchors").append('<option id="'+result[i].id+'" value="'+result[i].anchor+'">'+result[i].anchor+'</option>');
            }
            $("#anchor_text").val(result[0].anchor);
        });
    });
$.each(result, function(key, value) {   
    $('#anchors')
    .append($('<option>', { value : key })
    .text(value)); 
});