2017-02-18 7 views
0

Я пытаюсь вызвать веб-сервис через некоторое Jquery, но я получаю следующее сообщение об ошибкеСледующая вебсервис с вызова веб-службы не работает

ERR_SPDY_PROTOCOL_ERROR

Когда я пытаюсь получить доступ к веб-службы через браузер, я получаю ответ обратно,

https://vik-b-it.000webhostapp.com/intergration.php?primaryRef=1&amount=2&fp=3

{ "Fingerprint": "1234 | Привет | 10 | 1 | 2 | 3"}

Но когда я вызываю его через следующий код, я получаю вышеуказанную ошибку. Что мне здесь не хватает?

код веб-службы

<?php 
 

 
/* require the user as the parameter */ 
 
if(isset($_GET['primaryRef']) && isset($_GET['amount']) && isset($_GET['fp'])) 
 
{ 
 

 
\t /*Set the variables */ 
 
\t 
 
\t $primaryRef \t = $_GET['primaryRef']; 
 
\t $amount \t \t = $_GET['amount']; 
 
\t $fp \t \t \t = $_GET['fp']; 
 
\t $merchantId \t = 1234; 
 
\t $password \t \t = 'Hello'; 
 
\t $txnType \t \t = 10; 
 
\t 
 
\t 
 
\t /* $results = 'This should be the return string'; */ 
 
\t $results = $merchantId . '|' . $password . '|' . $txnType . '|' . $primaryRef .'|' . $amount .'|' . $fp; 
 
\t //$results = sha1($results); 
 
\t 
 
\t header('Content-type: application/json'); 
 
\t echo json_encode(array('fingerPrint' =>$results)); 
 

 
\t 
 
} 
 

 
?>

код Javascript является

<html> 
 
<head> 
 

 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
<script> 
 

 
$(document).ready(function(){ 
 
    
 
    console.log('hello'); 
 
    
 
    GetFingerprint(1, 2, 3); 
 
    
 
    function GetFingerprint(primaryRefNo, amount, fp){ 
 
    
 
\t var divToBeWorkedOn = "#AjaxPlaceHolder"; 
 
    var webService = "https://vik-b-it.000webhostapp.com/intergration.php"; 
 
    var parameters = "{'primaryRef':'" + primaryRefNo + "','amount':'" + amount + "','fp':'" + fp + "'}"; 
 

 
    $.ajax({ 
 
     type: "GET", 
 
     url: webService, 
 
     data: parameters, 
 
     contentType: "application/json; charset=utf-8", 
 
     dataType: "json", 
 
     success: function(msg) { 
 
      $(divToBeWorkedOn).html(msg.d); 
 
     }, 
 
     error: function(e){ 
 
      $(divToBeWorkedOn).html("Unavailable"); 
 
     } 
 
    }); 
 
} 
 
    
 
}); 
 
</script> 
 
</head> 
 

 
<body> 
 

 
TEST PAGE 
 

 
<div id='AjaxPlaceHolder'> 
 

 
</div> 
 

 
</body> 
 

 

 
</html>

Благодаря

Если кто-то заинтересован окончательный рабочий код выглядит следующим образом,

Webservice ->

<?php 
/* require the user as the parameter */ 
if(isset($_GET['primaryRef']) && isset($_GET['amount']) && isset($_GET['fp'])) 
{ 
    /*Set the variables */ 
    $primaryRef  = $_GET['primaryRef']; 
    $amount   = $_GET['amount']; 
    $fp    = $_GET['fp']; 
    $merchantId  = 1234; 
    $password  = 'Hello'; 
    $txnType  = 10; 

    //Concatanate the values together 
    $results = $merchantId . '|' . $password . '|' . $txnType . '|' . $primaryRef .'|' . $amount .'|' . $fp; 
    // Hash the information 
    $results = sha1($results); 
    // Encode data as JSON 
    $returnValue = 'jsonpCallback(' . json_encode(array('fingerPrint' =>$results)) . ');'; 

    // change the content type 
    header('Content-type: application/javascript'); 
    echo $returnValue; 
} 
?> 

и код вызова JQuery ->

$(document).ready(function(){ 

    //Generate the UTC date time 
    GenerateUTCDateTime(); 

    //Generate the fingerprint and pass the values from the three hidden fields - primary_ref, amount, fp_timestamp 
    GetFingerprint($('[name=primary_ref]').val(), $('[name=amount]').val(), $('[name=fp_timestamp]').val()); 

    // function to ensure that all dates are returned as two digits 
    // i = the number to checked 
    // returns two digit number 
    function addZero(i) 
    { 
     if (i < 10) 
     { 
      i = "0" + i; 
     } 
     return i; 
    } 

    // function that generates the current date and time as UTC 
    function GenerateUTCDateTime() 
    { 
     var dNow = new Date(); 
     var utc = new Date(dNow.getTime() + dNow.getTimezoneOffset() * 60000) 
     var utcdate= utc.getFullYear() + addZero((utc.getMonth()+1)) + addZero(utc.getDate()) + addZero(utc.getHours()) + addZero(utc.getMinutes()) + addZero(utc.getSeconds()); 
     //asign the date and time to the hidden field fp_timestamp 
     $('[name=fp_timestamp]').val(utcdate); 
    } 

    // function that populates the hiddent field with the fingerprint generated 
    function GetFingerprint(primaryRefNo, amount, fp) 
    { 
     // make sure that the three input paramters are available, otherwise throw an error 
     if (!primaryRefNo || !amount || !fp) 
     { 
      alert('Could not find the required values, please contact [email protected]'); 
      return; 
     } 

     // web service URL 
     var webService = "https://vik-b-it.000webhostapp.com/intergration.php"; 
     // input parameters that are passed 
     var parameters = JSON.parse('{"primaryRef":' + primaryRefNo + ', "amount":' + amount + ', "fp":' + fp +'}'); 

     // make an ajax call to get the data 
     $.ajax({ 
      type: "GET", 
      url: webService, 
      data: parameters, 
      contentType: "application/json; charset=utf-8", 
      dataType: 'jsonp', 
      jsonp: false, 
      jsonpCallback: "jsonpCallback", 
      success: function(data) {  
       $('[name=fingerprint]').val(data.fingerPrint); 
      }, 
      error: function(e){ 
       alert('Error has occured, please contact [email protected]'); 
      } 
     }); 
    } 
}); 
+0

Попробуйте добавить? в конце webService var? Я не вижу его нигде в другом месте – Inkdot

+0

Также - вы изучили политику «того же происхождения»? это может иметь какое-то отношение к этому. – Inkdot

ответ

0

Поскольку данные вы передаете to ajax недействителен

Вы ожидали JSON, но вы передавали строку

var parameters = "{'primaryRef':'" + primaryRefNo + "','amount':'" + amount + "','fp':'" + fp + "'}"; 

Так что попробуйте изменить его актуальному JSON Здесь намек

var parameters = {primaryRef: primaryRefNo, amount: amount, fp: fp}; 
+0

Спасибо за подсказку. Как вы указали, мне пришлось пройти в объекте Json. Я обновил свой вопрос с помощью кода решения, если кому-то еще интересно. – user2206329